[R] efficient way to do 2-level loops
Jie
jimmycloud at gmail.com
Thu Sep 6 16:50:00 CEST 2012
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
More information about the R-help
mailing list