【问题标题】:R dataframe: How to split by 2 columns and calculate the meanR数据框:如何分成2列并计算平均值
【发布时间】:2017-12-20 16:40:26
【问题描述】:

我有一个包含这样几列的数据框:

(我有很多列要计算平均值,所以我不能按名称来处理它们)

df:
  A    B    C     D     E     F....
  1    1    10    ...   ...   ...
  1    1    30    ...   ...   ...
  1    2    100   ...   ...   ...
  1    2    300   ...   ...   ...
  2    1    4     ...   ...   ...
  2    1    6     ...   ...   ...
  2    1    8     ...   ...   ...

现在我想将此数据帧拆分为 A 组和 B 组并计算平均值:

A=1:
    B=1: mean = 20
    B=2: mean = 200
A=2:
    B=1: mean = 6

我该怎么做?

谢谢!

【问题讨论】:

  • 使用dplyr 你可以df %>% group_by(A, B) %>% summarise(mean=mean(C))
  • Raggregate(C ~ A + B, data = df, FUN = mean)为基数。

标签: r dataframe split mean


【解决方案1】:

您可以为此使用dplyr

对于

library(dplyr)
df %>%
  gather("Col","Numbers", C:length(.)) %>%
  group_by(A, B) %>%
  summarise(mean = mean(Numbers))

最好的,

科林

【讨论】:

    猜你喜欢
    • 2018-04-10
    • 2020-12-16
    • 1970-01-01
    • 1970-01-01
    • 2017-12-04
    • 2015-10-12
    • 2016-02-03
    • 1970-01-01
    • 2021-07-19
    相关资源
    最近更新 更多