简体   繁体   中英

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 ?

We can place the vectors in a list , pad NA for list elements that have less number of element and do the 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

cbind the data with fill option as NA and apply colMeans on the t ranspose of the data.frame

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:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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