[R] How to create arbitrary number of loops in R

ilai keren at math.montana.edu
Thu Mar 29 17:46:19 CEST 2012

```On Thu, Mar 29, 2012 at 9:27 AM, ilai <keren at math.montana.edu> wrote:

Oops, sent to fast. A (maybe) clearer solution:

f <- function(x,m){
cmway <- combn(ncol(x),m)
xx <- x[,cmway]
dim(xx) <- c(nrow(x),nrow(cmway),ncol(cmway))
xx
}

f(M,3)
str(sapply(2:4,f,x=M))

And again lapply / apply , or even return icc(xx) in f

Cheers

> To cbind, you don't need a loop
>
> (M <- matrix(1:50,nc=10))
> c2way <- combn(ncol(M),2)
> MM <- M[,c2way]
> dim(MM) <- c(nrow(M),nrow(c2way),ncol(c2way))
> MM
>
> c3way <- combn(ncol(M),3)
> MMM <- M[,c3way]
> dim(MMM) <- c(nrow(M),nrow(c3way),ncol(c3way))
> MMM
>
> etc. etc.
>
> Than you can (untested for icc) loop your function as in
> apply(MMM,3,somefun)
>
> cheers
>
> On Thu, Mar 29, 2012 at 7:28 AM, Dai, Hongying, <hdai at cmh.edu> wrote:
>> Dear R users,
>>
>> I'm wondering how I can generate an arbitrary number of loops in R.
>> For instance, I can generate two "for" loops to get ICC among any two-way combination among 10 variables. Here is the code
>>
>> n<-10
>> for (i in 1:(n-1))
>> {
>> for (j in (i+1):n)
>> {
>> icc(cbind(DATA[,i],DATA[,j]))
>> }
>> }
>> If I need three-way combination, then a code with three "for" loops will be:
>> n<-10
>> for (i in 1:(n-2))
>> {
>> for (j in (i+1):(n-1))
>> {
>> for (k in (j+1):n)
>> {
>> icc(cbind(DATA[,i],DATA[,j],DATA[,k]))
>> }
>> }
>> }
>> But how can I write a code if I need all m=2, 3, 4,... loops for arbitrary m-way combinations?
>> Thanks!
>> Daisy
>>
>>
>> ________________________________
>> Electronic mail from Children's Mercy Hospitals and Clinics. This communication is intended only for the use of the addressee. It may contain information that is privileged or confidential under applicable law. If you are not the intended recipient or the agent of the recipient, you are hereby notified that any dissemination, copy or disclosure of this communication is strictly prohibited. If you have received this communication in error, please immediately forward the message to Children's Mercy Hospital's Information Security Officer via return electronic mail at informationsecurityofficer at cmh.edu and expunge this communication without making any copies. Thank you for your cooperation.
>>
>>        [[alternative HTML version deleted]]
>>
>> ______________________________________________
>> R-help at r-project.org mailing list
>> https://stat.ethz.ch/mailman/listinfo/r-help