[R] apply over list of data.frames

Joshua Wiley jwiley.psych at gmail.com
Wed Nov 24 20:48:00 CET 2010


Hi Tim,

It may not be possible, but if you can use an array, it is super easy:

## convert to array
Sue <- array(unlist(x), dim = c(3, 3, 2))

## use apply() on first two dimensions (collapse across 3rd)
apply(X = Sue, MARGIN = c(1, 2), FUN = mean)

Cheers,

Josh

On Wed, Nov 24, 2010 at 11:37 AM, Tim Howard
<tghoward at gw.dec.state.ny.us> 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.
>



-- 
Joshua Wiley
Ph.D. Student, Health Psychology
University of California, Los Angeles
http://www.joshuawiley.com/



More information about the R-help mailing list