Skip to content

lapply and for

1 message · Venables, Bill (CMIS, Cleveland)

#
Agustin Lobo asks (and I interpolate in his question)
If you want to make the for() option as slick as possible you should avoid
growing an object inside the loop.  In this case a better way of doing it
would be:

a <- structure(numeric(length(milista)), names = names(milista))
for(i in 1:length(milista)) a[i] <- mean(milista[[i]])
assume that milista has unique names.  It also labels the elements of a with
the names of milista, if such exist.
As always in these matters, it depends, but you will need to have a very
long list indeed before you notice the difference, I'd say.  To get an
exactly equivalent, though you need to do

a <- unlist(lapply(milista, mean))

but even then the gain in simplicity for the same outcome is heavily on the
side of the lapply option, I reckon.

Bill Venables.
-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.
-.-
http://www.ci.tuwien.ac.at/~hornik/R/R-FAQ.html
_._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._.
_._
-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
r-help mailing list -- Read http://www.ci.tuwien.ac.at/~hornik/R/R-FAQ.html
Send "info", "help", or "[un]subscribe"
(in the "body", not the subject !)  To: r-help-request at stat.math.ethz.ch
_._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._