Skip to content
Prev 12481 / 398502 Next

lapply and for

Agustin Lobo <alobo at ija.csic.es> writes:
Probably, since the first option is far from optimal itself:

a <- numeric(length(milista))
n <- 0
for (i in milista) 
   a[n <- n + 1] <- mean(i)

or 

n <- length(milista)
a <- numeric(n)
for (i in 1:n)
    a[i] <- mean(milista[[i]])

should both be faster. lapply essentially *is* the latter, but has the
for loop coded in C, so should be faster, but not by a huge amount.
For very short lists, the "red tape" at the beginning and end of
lapply() might pull in the opposite direction.

Why not just try it and see?