R中不等长列表的平均值

3

我有一组长度不同的向量列表。我想要的是每个索引的平均数值。例如:

a = c(2,3,4)
b = c(2,3,4,5) 
c = c(5,0,3,4,6)

avg(a,b,c) = c(9/3, 6/3, 11/3, 9/2, 6/1)

如何在R中实现这一目标?
3个回答

7
我们可以将向量放入一个list中,对于元素数量较少的列表元素进行NA填充,然后使用rowMeans函数。
lst <- list(a, b, c)
rowMeans(sapply(lst, `length<-`, max(lengths(lst))), na.rm=TRUE)
#[1] 3.000000 2.000000 3.666667 4.500000 6.000000

数据

a <- 2:4
b <- 2:5
c <- c(5, 0, 3, 4, 6)

3
你可以使用rowr包中的cbind.fill函数。
使用fill选项用NA填充数据,然后对数据框的transpose应用colMeans函数。
library(rowr)
colMeans(t(cbind.fill(a, b, c, fill = NA)), na.rm = T)

#[1] 3.000000 2.000000 3.666667 4.500000 6.000000

1
这个使用基础 R 的怎么样:
ls <- list(a, b, c)
sapply(1:max(lengths(ls)), function(i) mean(sapply(ls, function(x) x[i]), na.rm = T))

# [1] 3.000000 2.000000 3.666667 4.500000 6.000000

这个想法是在列表中的每个向量的第1、2、3等位置上应用mean函数,并忽略NA值。

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