列表中列表的向量平均值

4
我有一个列表,其结构如下:
> 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

我希望能够得到mylist中向量ab的逐元素均值。对于向量a,结果将是这样的:
> a
[1] 3.5 4.5 5.5

我知道函数lapplyrbindcolMeans,但是我无法用它们解决问题。我该如何实现我需要的功能?

5个回答

6

这里有一种方法,使用“reshape2”中的meltdcast

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

这是一个基于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 

这个“unlist”更好,更干净!我一开始对使用“recursive = T”非常怀疑,并没有注意到可能存在的分组因素。 - alexis_laz

4

更新: 更好的方法是使用sapply(mylist,unlist),它实际上提供了一个很好的矩阵可以应用rowMeans

> rowMeans(sapply(mylist, unlist))
#  a1  a2  a3  b1  b2  b3 
# 3.5 4.5 5.5 5.5 6.5 7.5 

翻译:

另一种使用lapply方法的方式,其中还包括sapply
> lapply(1:2, function(i) rowMeans(sapply(mylist, "[[", i)) )
# [[1]]
# [1] 3.5 4.5 5.5
#
# [[2]]
# [1] 5.5 6.5 7.5

2

另一个想法:


tmp = unlist(mylist, F)
sapply(unique(names(tmp)), 
       function(x) colMeans(do.call(rbind, tmp[grep(x, names(tmp))])))
#       a   b
#[1,] 3.5 5.5
#[2,] 4.5 6.5
#[3,] 5.5 7.5

+1。我刚刚也发布了一个关于unlist的答案,但与这个有很大不同 :-) - A5C1D2H2I1M1N2O1R2T1

2
这是一个使用data.tableRcppRoll组合的方法(对于大列表应该非常快)。
library(data.table)
library(RcppRoll)
roll_mean(as.matrix(rbindlist(mylist)), 4, weights=c(1,0,0,1))

##     [,1] [,2]
## [1,]  3.5  5.5
## [2,]  4.5  6.5
## [3,]  5.5  7.5

1

通过data.frame的一种可能的方法之一

mylist <- list(list(a = 1:3, b = 4:6),list(a = 6:8, b = 7:9))

sapply(c("a","b"),function(x){
  listout <- lapply(mylist,"[[",x)
  rowMeans(do.call(cbind,listout))
})

       a   b
[1,] 3.5 5.5
[2,] 4.5 6.5
[3,] 5.5 7.5

1
这不是正确的结果。(1+6)/2 == 3.5,而不是2.5。 - GSee

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接