列表列表中的矢量的平均值

Jon*_*ann 4 r list mean

我有一个列表列表,其中包含以下结构:

> mylist <- list(list(a=as.numeric(1:3), b=as.numeric(4:6)), 
                 list(a=as.numeric(6:8), b=as.numeric(7:9)))
> str(mylist)
List of 2
 $ :List of 2
  ..$ a: num [1:3] 1 2 3
  ..$ b: num [1:3] 4 5 6
 $ :List of 2
  ..$ a: num [1:3] 6 7 8
  ..$ b: num [1:3] 7 8 9
Run Code Online (Sandbox Code Playgroud)

我想获得的向量之间逐元素均值abmylist.对于向量a,结果将是:

> a
[1] 3.5 4.5 5.5
Run Code Online (Sandbox Code Playgroud)

我了解的功能lapply,rbindcolMeans但我不能与他们解决这个问题.我怎样才能达到我的需要?

A5C*_*2T1 6

这是一种使用meltdcast来自"reshape2"的方法.

library(reshape2)

## "melt" your `list` into a long `data.frame`
x <- melt(mylist)

## add a "time" variable to let things line up correctly
## L1 and L2 are created by `melt`
## L1 tells us the list position (1 or 2)
## L2 us the sub-list position (or name)
x$time <- with(x, ave(rep(1, nrow(x)), L1, L2, FUN = seq_along))

## calculate whatever aggregation you feel in the mood for
dcast(x, L2 ~ time, value.var="value", fun.aggregate=mean)
#   L2   1   2   3
# 1  a 3.5 4.5 5.5
# 2  b 5.5 6.5 7.5
Run Code Online (Sandbox Code Playgroud)

这是基础R中的一种方法:

x <- unlist(mylist)
c(by(x, names(x), mean))
#  a1  a2  a3  b1  b2  b3 
# 3.5 4.5 5.5 5.5 6.5 7.5 
Run Code Online (Sandbox Code Playgroud)