【问题标题】:Group by, pivot, count and sum in DF in RR中DF中的分组,透视,计数和求和
【发布时间】:2019-05-08 20:16:57
【问题描述】:

我有一个日期框架,其中包含 PARTIDA(日期)、Operação(4 级因子)和 TT(数字)字段。

我需要按 PARTIDA 列分组,将 Operation 列计数到每个级别的频率,然后对 TT 列求和。 像这样:

我已经用 dplyr 尝试了一些东西,但我无法得到这个结果,谁能帮助我?

【问题讨论】:

  • 你能不能把输入例子的dput贴出来而不是一张图片(难测)

标签: r dplyr


【解决方案1】:

这里有一个两步过程,可以得到你想要的:

library(dplyr)

df <- 
  tibble(
    partida = c("date1", "date2", "date3", "date1", "date2"),
    operacao = c("D", "J", "C", "D", "M"),
    tt = c(1, 2, 3, 4, 5)
  )

tt_sums <- 
  df %>% 
  group_by(partida) %>% 
  count(wt = tt)

operacao_counts <-
  df %>% 
  group_by(partida, operacao) %>% 
  count() %>% 
  ungroup() %>% 
  spread(operacao, n) %>% 
  mutate_if(is.numeric, replace_na, 0)

final_df <-
  operacao_counts %>% 
  left_join(tt_sums, by = "partida")

> final_df
# A tibble: 3 x 6
  partida     C     D     J     M     n
  <chr>   <dbl> <dbl> <dbl> <dbl> <dbl>
1 date1       0     2     0     0     5
2 date2       0     0     1     1     7
3 date3       1     0     0     0     3

【讨论】:

    【解决方案2】:

    类似于@cardinal40 的回答,但我尝试尽可能限制添加到我的环境中的对象数量。任何一个答案都可以解决问题。

    df %>% 
      group_by(partida) %>% 
      mutate(tt = sum(tt)) %>% 
      group_by(partida, operacao, tt) %>% 
      count() %>% 
      ungroup() %>% 
      spread(operacao, n) %>% 
      mutate_if(is.numeric, replace_na, 0)
    
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-15
      • 2017-02-28
      相关资源
      最近更新 更多