[R] efficient way to do 2-level loops

Rui Barradas ruipbarradas at sapo.pt
Thu Sep 6 17:31:38 CEST 2012


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.




More information about the R-help mailing list