[R] how to get output from a nested loop

Linlin Yan yanlinlin82 at gmail.com
Wed Jun 10 08:08:03 CEST 2009


How about like this:
> t1 <- data.frame(row.names=c('c1','c2','c3','c4'), mk1=c(1,1,0,0), mk2=c(0,0,0,1), mk3=c(1,1,1,1), mk4=c(0,0,0,0), mk5=c(0,0,0,1), S=c(4,5,3,2))
> t1
   mk1 mk2 mk3 mk4 mk5 S
c1   1   0   1   0   0 4
c2   1   0   1   0   0 5
c3   0   0   1   0   0 3
c4   0   1   1   0   1 2
> apply(combn(1:5, 2), 2, function(x) t1[,c(x[1], 6, x[2])])
[[1]]
   mk1 S mk2
c1   1 4   0
c2   1 5   0
c3   0 3   0
c4   0 2   1
... ...

On Wed, Jun 10, 2009 at 1:10 PM, Scott Hermann<SHermann at bses.org.au> wrote:
> Dear all,
>
> I imagine that this is a trival question, but it has perplexed for most of the day.  Any help would be greatly appreciated.
>
> Below is an example of what I'm trying to do.
>
> Essentially I want to produce all unique 1 x 1 combinations of certain columns from a dataframe, and join these to other columns from the same dataframe.  I'm having problems with the nested loop as I can only output data from the last "cycle" of the loop.  I realise that the problem is with the st1[[i]] but I'm not sure how to define it differently.
>
> ##I want to make a list file of all 1x1 combinations of "mk" columns, and add "clone" and "S" to these combinations.
>
> clone<-c("c1","c2","c3","c4")
> mk1<-c(1,1,0,0)
> mk2<-c(0,0,0,1)
> mk3<-c(1,1,1,1)
> mk4<-c(0,0,0,0)
> mk5<-c(0,0,0,1)
> S<-c(4,5,3,2)
> t1<-as.data.frame(cbind(clone,mk1,mk2,mk3,mk4, mk5,S))
> row.names(t1)<-t1$clone
> t1<-t1[,-1]
> t1
>
> ###A nested loop.  I'm trying to get all combinations of columns 1:5 and join each of them with column 7.
>
> st1 <- list()
>  for(i in 1:4) {
>   for(j in (i+1):5){
>       st1[[i]] <- cbind(t1[,c(i,6)],t1[,j])
>       }
>       }
>  st1
>
> Thanks for your help,
>
> Scott
> BSES Limited Disclaimer
>
> --------------------------------------------------------------------------------
>
> This email and any files transmitted with it are confide...{{dropped:13}}
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>




More information about the R-help mailing list