[R] apply over list of data.frames

Dimitris Rizopoulos d.rizopoulos at erasmusmc.nl
Wed Nov 24 20:43:57 CET 2010


try this:

DF.lis <- list(
     one = data.frame(x = c(1,2,3), y = c(1,2,2), z = c(3,1,1)),
     two = data.frame(x = c(2,5,2), y = c(2,3,1), z = c(4,1,2))
)

Reduce("+", DF.lis) / length(DF.lis)


I hope it helps.

Best,
Dimitris


On 11/24/2010 8:37 PM, Tim Howard wrote:
> R users,
> This probably involves a simple incantation of one of the flavors of apply... that I can't yet figure out. Consider a list of data frames. I'd like to apply a function (mean) across the list and return a dataframe of the same dimensions where each cell represents the mean of that cell across all dataframes.
>
> # set up the list
> x<- vector("list",2)
> names(x)<- c("one","two")
> # add data to the list
> for(i in 1:2){
>   y = i^2
>   x[[i]]<- data.frame("a"=c(y,2*y,3*y),"b"=c(y+1,y+2,y+3),"c"=c(2*y+1,2*y+2,2*y+3))
>   }
> #show the list
>> x
> $one
>    a b c
> 1 1 2 3
> 2 2 3 4
> 3 3 4 5
>
> $two
>     a b  c
> 1  4 5  9
> 2  8 6 10
> 3 12 7 11
> #the result should be
>   a b c
> 1 2.5 3.5 6
> 2 5 4.5 7
> 3 7.5 5.5 8
>
> Can anyone direct me down the right path?
>
> Thanks in advance
> Tim Howard
>
>
>
>
> 	[[alternative HTML version deleted]]
>
> ______________________________________________
> R-help at r-project.org 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.
>

-- 
Dimitris Rizopoulos
Assistant Professor
Department of Biostatistics
Erasmus University Medical Center

Address: PO Box 2040, 3000 CA Rotterdam, the Netherlands
Tel: +31/(0)10/7043478
Fax: +31/(0)10/7043014
Web: http://www.erasmusmc.nl/biostatistiek/



More information about the R-help mailing list