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:5) { resu[i,j]=a[i]+b[j] # will be more complicated } } # Do I have to create a list like this i order to use sapply? data=list() for (i in 1:5) { for (j in 1:5) { data[[(i-1)*5+j]]=list(a=a[i],b=b[j]) } } Thank you for your attention. Best wishes, Jie
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 } } f <- function(i, j) a[i] + b[j] mat <- expand.grid(a, b) res2 <- apply(mat, 1, function(ii) f(ii[1], ii[2])) res2 <- matrix(res2, nrow = 5) identical(resu, res2) # TRUE Hope this helps, Rui Barradas Em 06-09-2012 15:50, Jie escreveu:> 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:5) > { > resu[i,j]=a[i]+b[j] # will be more complicated > } > } > # Do I have to create a list like this i order to use sapply? > data=list() > for (i in 1:5) > { > for (j in 1:5) > { > data[[(i-1)*5+j]]=list(a=a[i],b=b[j]) > } > } > > Thank you for your attention. > Best wishes, > Jie > > ______________________________________________ > 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.
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:10 > resu <- matrix(NA,nrow=5,ncol=10) > for (i in 1:5) > { > for (j in 1:5) > { > resu[i,j]=a[i]+b[j] # will be more complicated > } > }Hi. For this part, when the output is a matrix, try the following. a <- 1:5 b <- 1:10 f <- function(a, b) { a+b } resu <- outer(a, b, FUN=f) resu [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] [1,] 2 3 4 5 6 7 8 9 10 11 [2,] 3 4 5 6 7 8 9 10 11 12 [3,] 4 5 6 7 8 9 10 11 12 13 [4,] 5 6 7 8 9 10 11 12 13 14 [5,] 6 7 8 9 10 11 12 13 14 15 Hope this helps. Petr Savicky.