Re: [R] efficient way to do 2-level loops

2012-09-06 Thread Petr Savicky
On Thu, Sep 06, 2012 at 10:50:00AM -0400, Jie wrote: > Dear All, > > Suppose I have two loops and would like to convert it to sapply, how > to achive the goal? > Below is an example, the calculation inside the loop is not essential, > so please do not use tricks for this part. > a <- 1:5 > b <- 1:

Re: [R] efficient way to do 2-level loops

2012-09-06 Thread Rui Barradas
Hello, Use expand.grid. One line at a time, to make it clearer: a <- 1:5 b <- 1:10 m <- expand.grid(b, a)[, c(2, 1)] resu <- matrix(NA, nrow=5, ncol=10) for (i in 1:5) { for (j in 1:10) # --> was 1:5 in your post { resu[i,j]=a[i]+b[j] # will be more complicated } }

[R] efficient way to do 2-level loops

2012-09-06 Thread Jie
Dear All, Suppose I have two loops and would like to convert it to sapply, how to achive the goal? Below is an example, the calculation inside the loop is not essential, so please do not use tricks for this part. a <- 1:5 b <- 1:10 resu <- matrix(NA,nrow=5,ncol=10) for (i in 1:5) { for (j in 1: