【问题标题】:Sum up integers by group longwise in R [duplicate]在R中按组长求和整数[重复]
【发布时间】:2021-08-17 08:09:25
【问题描述】:

我希望按 id 组添加值列,并将总计放在每个 id 的 type = total 的位置。 在下面的示例中,id = 1 的总数将为 5 而不是 NA,id = 2 的总数将为 17 而不是 NA。

可能存在不应包含在总和中的 NA 值。

df <- data.frame(id = c(1, 1, 1, 1, 2, 2, 2, 2), type = c('A', 'B', 'C', 'total', 'A', 'B', 'C', 'total'), value = c('1', NA, '4', NA, '5', '4', '8', NA))


 id  type value
  1     A     1
  1     B  <NA>
  1     C     4
  1 total  <NA>
  2     A     5
  2     B     4
  2     C     8
  2 total  <NA>

这将是所需的输出:

 id  type value
  1     A     1
  1     B  <NA>
  1     C     4
  1 total     5
  2     A     5
  2     B     4
  2     C     8
  2 total    17

据我所知,group_by() 是迈向答案的第一步?但我不确定如何使用组中的值将其分配给总数。也许 colSums()?

任何帮助将不胜感激,谢谢!

【问题讨论】:

标签: r dplyr


【解决方案1】:

这应该可行,我认为足够清楚。

df %>%
  group_by(id) %>%
  mutate(
    value = as.numeric(value),
    value = if_else(type == 'total', sum(value, na.rm = T), value)
  )

另一个值得一读的选项是janitor 包。

【讨论】:

    【解决方案2】:

    我不介意从没有总行数的数据框开始,您可以执行以下操作:

    # I changed your data so value is of type numeric, you could use mutate(value = as.numeric(value)) if necessary
    # and there is no total anymore as the code creates this line from raw data
    
    df <- data.frame(id = c(1, 1, 1, 2, 2, 2), 
                     type = c('A', 'B', 'C', 'A', 'B', 'C'), 
                     value = c(1, NA, 4, 5, 4, 8))
    
    library(dplyr)
    
    df %>% 
      group_by(id) %>% 
      summarise(value = sum(value, na.rm = TRUE),
                type = "total") %>% 
      bind_rows(., df) %>% 
      # some sorting for a better looking table
      select(id, type, value) %>% 
      mutate(type = forcats::fct_relevel(.f = type, "total", after = Inf)) %>% 
      arrange(id, type)
    
    #> # A tibble: 8 x 3
    #>      id type  value
    #>   <dbl> <fct> <dbl>
    #> 1     1 A         1
    #> 2     1 B        NA
    #> 3     1 C         4
    #> 4     1 total     5
    #> 5     2 A         5
    #> 6     2 B         4
    #> 7     2 C         8
    #> 8     2 total    17
    

    reprex package (v2.0.0) 于 2021-08-17 创建

    【讨论】:

      猜你喜欢
      • 2019-02-24
      • 2023-03-20
      • 2015-06-01
      • 2014-08-22
      • 2013-05-30
      • 2021-09-22
      • 2015-12-31
      • 1970-01-01
      • 2015-03-23
      相关资源
      最近更新 更多