[R] calculating mean of list components
Liviu Andronic
landronimirc at gmail.com
Wed Dec 15 15:05:37 CET 2010
On Wed, Dec 15, 2010 at 2:22 PM, Jim Maas <jimmaasuk at gmail.com> wrote:
> I get a list object from an iterative function. I'm trying to figure out
> the most efficient way to calculate the mean of one element, across all
> components of the overall list.
>
> I've tried
>
> output <- mean (listobject[[1:5]]$element)
>
> to get the mean of "element" in the first five components?
>
> It doesn't like the $. I'm suspect one of the "apply" functions will work,
> but again I've not had success
>
Are you looking for this?
> x <- list()
> x[[1]] <- list()
> x[[1]][['element']] <- rnorm(100)
> x[[2]] <- list()
> x[[2]][['element']] <- rnorm(100)
> x[[3]] <- list()
> x[[3]][['element']] <- rnorm(100)
> str(x)
List of 3
$ :List of 1
..$ element: num [1:100] 1.822 1.818 -2.305 -0.307 0.268 ...
$ :List of 1
..$ element: num [1:100] 0.0167 0.3834 1.2947 -0.4583 -0.2165 ...
$ :List of 1
..$ element: num [1:100] -1.244 -0.369 0.772 -2.368 2.136 ...
> mean(x[[1]][['element']])
[1] 0.1446610
> mean(x[[2]][['element']])
[1] -0.1471191
> mapply(function(y) mean(y$element), x)
[1] 0.14466105 -0.14711910 0.05024247
Liviu
More information about the R-help
mailing list