wes*_*352 0 r list vector mean
我有一个非常大的 list() ,其中有超过 2000 个元素,其中每个元素都有两个向量(x 和 y),列表元素之间的大小不同。
例子:
new_list<-list(data.frame(x = c(1,2,3),
y = c(3,4,5)),
data.frame(x = c(3,2,2,2,3,8),
y = c(5,2,3,5,6,7)),
data.frame(x = c(3,2,2,1,1),
y = c(5,2,3,3,2)))
Run Code Online (Sandbox Code Playgroud)
我只想对x这个列表中的向量进行平均以获得如下结果:
df_mean<-data.frame(x=c(2,3.333,1.8))
Run Code Online (Sandbox Code Playgroud)
您可以像这样计算colMeans每列包含 x 的数据sapply:
data.frame(x = sapply(new_list, \(x) colMeans(x[grepl('x', names(x))])))
#> x
#> 1 2.000000
#> 2 3.333333
#> 3 1.800000
Run Code Online (Sandbox Code Playgroud)
@nicola 建议了一个更好的选择,如下所示(谢谢!):
data.frame(x = sapply(new_list, \(x) mean(x$x)))
#> x
#> 1 2.000000
#> 2 3.333333
#> 3 1.800000
Run Code Online (Sandbox Code Playgroud)
创建于 2023-02-06,使用reprex v2.0.2