汇总具有不同功能的不同列

Max*_*Max 5 statistics group-by r dataframe

我有以下问题:在数据框中,我有很多行和列,其中第一行是日期。对于每个日期,我都有1个以上的观察值,我想对其进行总结。

我的df看起来像这样(为了易于使用,将日期替换为ID):

df:
ID     Cash    Price    Weight   ...
1      0.4     0        0
1      0.2     0        82       ...
1      0       1        0        ...
1      0       3.2      80       ...
2      0.3     1        70       ...
...    ...     ...      ...      ...
Run Code Online (Sandbox Code Playgroud)

我想按第一列对它们进行分组,然后用不同的功能总结所有行,但:

函数Cash and Price应该是求和,所以我得到每个ID的Cash和Price的总和。重量上的功能应为最大,因此我只能获得ID的最大重量。

因为我有很多列,所以我不能手动编写所有函数,但是我只有2列,应该由max总结,其余的应该由sum总结

因此,我正在寻找一个按ID分组的函数,用总和汇总所有内容,但我需要最大值的 2个不同列除外。

我尝试将dplyr软件包用于:

df %>% group_by(ID = tolower(ID)) %>% summarise_each(funs(sum))
Run Code Online (Sandbox Code Playgroud)

但是我需要加法运算,而不是求和,但最多2个指定的列,是否有想法?

为了清楚起见,示例df的输出应为:

ID     Cash     Price    Weight
1       0.6        4.2       82     
2       0.3        1          70
Run Code Online (Sandbox Code Playgroud)

小智 7

从 dplyr 1.0.0 开始,您可以使用 across():

tribble(
  ~ID, ~max1, ~max2, ~sum1, ~sum2, ~sum3,
  1, 1, 1, 1, 2, 3,
  1, 2, 3, 1, 2, 3,
  2, 1, 1, 1, 2, 3,
  2, 3, 4, 2, 3, 4,
  3, 1, 1, 1, 2, 3,
  3, 4, 5, 3, 4, 5,
  3, NA, NA, NA, NA, NA
) %>%
  group_by(ID) %>%
  summarize(
    across(matches("max1|max2"), max, na.rm = T),
    across(!matches("max1|max2"), sum, na.rm = T)
  )

# ID  max1  max2  sum1  sum2  sum3
#  1     2     3     2     4     6
#  2     3     4     3     5     7
#  3     4     5     4     6     8
Run Code Online (Sandbox Code Playgroud)


akr*_*run 4

我们可以用

 df %>%
    group_by(ID) %>%
    summarise(Cash = sum(Cash), Price = sum(Price), Weight = max(Weight))
Run Code Online (Sandbox Code Playgroud)

如果我们有很多列,一种方法是单独执行此操作,然后join一起输出。

 df1 <- df %>% 
          group_by(ID) %>% 
          summarise_each(funs(sum), Cash:Price)
 df2 <- df %>%
          group_by(ID) %>% 
          summarise_each(funs(max), Weight)
 inner_join(df1, df2, by = "ID")
 #      ID  Cash Price Weight
 #   (int) (dbl) (dbl)  (int)
 #1     1   0.6   4.2     82
 #2     2   0.3   1.0     70
Run Code Online (Sandbox Code Playgroud)