[R] Avoiding loops & apply -function

Yohan Chalabi chalabi at phys.ethz.ch
Wed Nov 5 15:33:25 CET 2008


>>>> "DM" == David Masson <david.masson at env.ethz.ch>
>>>> on Wed, 05 Nov 2008 15:13:37 +0100

   DM> I have a question concerning avoiding loops.
   DM> I know the function "apply" and I have used it several times, but I feel 
   DM> blocked
   DM> with this situation :
   DM> 
   DM> E <- array(X, dim = c(L,nlon,nlat) )
   DM> data <- matrix(Y, nrow=nlon, ncol=nlat )
   DM> G <- vector(length=L)
   DM> 
   DM>    for (l in 1:L)
   DM>     {
   DM>       G[l] <- function.F(data,E[l,,])
   DM>     }
   DM> 
   DM> 
   DM> -  "E" is a 3-dimensional array filled with a given data X.
   DM> -  "data" is a (nlon*nlat) matrix filled with given data Y.
   DM> -  "G" is my output vector.
   DM> 
   DM> I want to apply the function "function.F", but this function has an 
   DM> argument that depends
   DM> on the index "l" ...

do you mean something like that?

sapply(1:L, function(idx, data, E) function.F(data, E[idx,,]), data, E)



More information about the R-help mailing list