【问题标题】:r - Overall mean of elements in list by rows and columnsr - 按行和列列出的元素的总体平均值
【发布时间】:2019-09-24 22:48:11
【问题描述】:

我需要获取 data.frames 列表中每一行和每一列的总体平均值:

set.seed(1)

df_1 = data.frame(a = rnorm(3), b = rnorm(3), c = rnorm(3))
df_2 = data.frame(a = rnorm(3), b = rnorm(3), c = rnorm(3))
df_3 = data.frame(a = rnorm(3), b = rnorm(3), c = rnorm(3))

df_lst = list(df_1, df_2, df_3)

这里我需要做以下事情:

mean(c(df_lst[[1]]$a[1], df_lst[[2]]$a[1], df_lst[[3]]$a[1]))
mean(c(df_lst[[1]]$a[2], df_lst[[2]]$a[2], df_lst[[3]]$a[2]))
mean(c(df_lst[[1]]$a[3], df_lst[[2]]$a[3], df_lst[[3]]$a[3]))

mean(c(df_lst[[1]]$b[1], df_lst[[2]]$b[1], df_lst[[3]]$b[1]))
mean(c(df_lst[[1]]$b[2], df_lst[[2]]$b[2], df_lst[[3]]$b[2]))
mean(c(df_lst[[1]]$b[3], df_lst[[2]]$b[3], df_lst[[3]]$b[3]))

mean(c(df_lst[[1]]$c[1], df_lst[[2]]$c[1], df_lst[[3]]$c[1]))
mean(c(df_lst[[1]]$c[2], df_lst[[2]]$c[2], df_lst[[3]]$c[2]))
mean(c(df_lst[[1]]$c[3], df_lst[[2]]$c[3], df_lst[[3]]$c[3]))

而期望的输出是:

> out
            a          b         c
1 -0.03687367  0.5853922 0.3541071
2  0.76310860 -0.6035424 0.2220019
3  0.15773067 -0.5616297 0.4546074

有什么建议吗?

【问题讨论】:

    标签: r list dataframe mean


    【解决方案1】:

    我们可以使用Reduce 得到元素总和(+),然后除以listlength

    Reduce(`+`, df_lst)/length(df_lst)
    #           a          b         c
    #1 -0.03687367  0.5853922 0.3541071
    #2  0.76310860 -0.6035424 0.2220019
    #3  0.15773067 -0.5616297 0.4546074
    

    或者将其转换为array,然后使用apply

    apply(array(unlist(df_lst), c(3, 3, 3)), 1:2, mean)
    

    【讨论】:

      猜你喜欢
      • 2013-07-22
      • 2017-06-11
      • 1970-01-01
      • 2016-05-02
      • 1970-01-01
      • 2016-08-23
      • 1970-01-01
      • 2017-10-25
      • 1970-01-01
      相关资源
      最近更新 更多