RE: [R] lapply and for

About this list Date view Thread view Subject view Author view Attachment view

From: Venables, Bill (CMIS, Cleveland) (Bill.Venables@CMIS.CSIRO.AU)
Date: Mon 23 Jul 2001 - 09:12:14 EST


Message-id: <E09E527B56BE2D438A3D6A246DDD27A99DA1@Roper-CV.qld.cmis.csiro.au>

Agustin Lobo asks (and I interpolate in his question)

> -----Original Message-----
> From: Agustin Lobo [mailto:alobo@ija.csic.es]
> Sent: Monday, 23 July 2001 7:45 AM
> To: r-help
> Subject: [R] lapply and for
>
>
> 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]])))
> + }

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]])

>From a programming point of view this is also preferable as it does not
assume that milista has unique names. It also labels the elements of a with
the names of milista, if such exist.

> or
>
> a <- lapply(milista,mean)
>
>
> ?

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.

>
> (I understand that the second option
> is nicer and more compact, but is it
> faster?).
>
> Thanks
>
> Agus
>
> Dr. Agustin Lobo
> Instituto de Ciencias de la Tierra (CSIC)
> Lluis Sole Sabaris s/n
> 08028 Barcelona SPAIN
> tel 34 93409 5410
> fax 34 93411 0012
> alobo@ija.csic.es
>
>
>
-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.
-.-
> 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@stat.math.ethz.ch
>
_._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._.
_._
-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
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@stat.math.ethz.ch
_._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._


About this list Date view Thread view Subject view Author view Attachment view

This archive was generated by hypermail 2.1.3 : Wed 10 Mar 2004 - 08:18:21 EST