[R] do.call vs. lapply for lists
Gabor Grothendieck
ggrothendieck at gmail.com
Mon Apr 9 19:19:43 CEST 2007
Consider this. If L is a list with n components then
- do.call(f, L) calls f once
- lapply(L, f) calls f n times
On 4/9/07, Muenchen, Robert A (Bob) <muenchen at utk.edu> wrote:
> Hi All,
>
> I'm trying to understand the difference between do.call and lapply for
> applying a function to a list. Below is one of the variations of
> programs (by Marc Schwartz) discussed here recently to select the first
> and last n observations per group.
>
> I've looked in several books, the R FAQ and searched the archives, but I
> can't find enough to figure out why lapply doesn't do what do.call does
> in this case. The help files & newsletter descriptions of do.call sound
> like it would do the same thing, but I'm sure that's due to my lack of
> understanding about their specific terminology. I would appreciate it if
> you could take a moment to enlighten me.
>
> Thanks,
> Bob
>
> mydata <- data.frame(
> id = c('001','001','001','002','003','003'),
> math = c(80,75,70,65,65,70),
> reading = c(65,70,88,NA,90,NA)
> )
> mydata
>
> mylast <- lapply( split(mydata,mydata$id), tail, n=1)
> mylast
> class(mylast) #It's a list, so lapply will so *something* with it.
>
> #This gets the desired result:
> do.call("rbind", mylast)
>
> #This doesn't do the same thing, which confuses me:
> lapply(mylast,rbind)
>
> #...and data.frame won't fix it as I've seen it do in other
> circumstances:
> data.frame( lapply(mylast,rbind) )
>
> =========================================================
> Bob Muenchen (pronounced Min'-chen), Manager
> Statistical Consulting Center
> U of TN Office of Information Technology
> 200 Stokely Management Center, Knoxville, TN 37996-0520
> Voice: (865) 974-5230
> FAX: (865) 974-4810
> Email: muenchen at utk.edu
> Web: http://oit.utk.edu/scc,
> News: http://listserv.utk.edu/archives/statnews.html
>
> ______________________________________________
> R-help at stat.math.ethz.ch mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>
More information about the R-help
mailing list