[R] efficient way to do 2-level loops
Petr Savicky
savicky at cs.cas.cz
Thu Sep 6 17:32:34 CEST 2012
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.
More information about the R-help
mailing list