简体   繁体   English

R中不等长度列表的平均值

[英]Average of list of unequal length in R

I have list of vectors of unequal lengths. 我有不等长的矢量列表。 What I want is the avg. 我想要的是平均值。 at each index. 在每个指数。 For example: 例如:

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)

How to achieve this in R ? 如何在R中实现这一目标?

We can place the vectors in a list , pad NA for list elements that have less number of element and do the rowMeans 我们可以将向量放在一个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

data 数据

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

You can use cbind.fill function in rowr package 您可以在rowr包中使用cbind.fill函数

cbind the data with fill option as NA and apply colMeans on the t ranspose of the data.frame cbind与数据fill选项作为NA和应用colMeanst的data.frame的ranspose

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

How about this using base R: 使用基数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

The idea is to apply the mean function on ls (on the 1th, 2th, 3th, ... of each vector in list) and ignoring NA values. 我们的想法是在ls上应用mean函数(在列表中每个向量的1th, 2th, 3th, ... )并忽略NA值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM