[R] lapply and for
Peter Dalgaard BSA
p.dalgaard at biostat.ku.dk
Mon Jul 23 01:28:13 CEST 2001
Agustin Lobo <alobo at ija.csic.es> writes:
> Given a list as such:
>
> > milista
> $"1":
> [1] 23 25 11
>
> $"2":
> [1] 34 2
>
> $"3":
> [1] 12 1 0 1050 2
>
> What's faster:
>
> > a <- NULL
> > for (i in names(milista)){
> + a <- c(a,(mean(milista[[i]])))
> + }
>
> or
>
> a <- lapply(milista,mean)
>
>
> ?
>
> (I understand that the second option
> is nicer and more compact, but is it
> faster?).
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?
--
O__ ---- Peter Dalgaard Blegdamsvej 3
c/ /'_ --- Dept. of Biostatistics 2200 Cph. N
(*) \(*) -- University of Copenhagen Denmark Ph: (+45) 35327918
~~~~~~~~~~ - (p.dalgaard at biostat.ku.dk) FAX: (+45) 35327907
-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
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
_._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._
More information about the R-help
mailing list