【问题标题】:R: Summation of Single Column Based on ConditionsR:基于条件的单列求和
【发布时间】:2018-04-08 00:35:58
【问题描述】:

我有一个数据集(在本网站的帮助下)基于 3 个实例创建了一个计数:

  1. Plans 的数量,其中Coins 大于 20
  2. Plans 的数量,其中Coins 等于 20
  3. Plans 的数量,其中Coins 小于 20

这是来自更大数据集的样本

Plan    Year   Coins   Copay   Enrollment
  A     2018     20      10       200
  B     2014     15       5       100
  C     2012     30       0        50
  D     2017     30      10       350
  E     2018     5       10       400
  F     2018     20       0       150
  G     2018     20       0       200
  H     2016     20      10       800
  I     2014     10       3       250
  J     2017     20       7       550

这是通过以下方式实现的:

df %>%
   group_by(grp = case_when(Coins < 20 ~ 'grp1', Coins ==20 ~ 'grp2', TRUE ~ 'grp3')) %>%
   summarise(Plan = toString(unique(Plan)), prop = n()) %>%
   ungroup %>%
   select(-grp)

获得:

  1. C, D - 2
  2. A、F、G、H、J - 5
  3. B、E、I - 3

我现在想涉及Enrollment 列并根据上述三个条件求和。因此,我想达到以下几点:

  1. 400 (50+350)
  2. 1900(200+150+200+800+550)
  3. 750 (100+400+250)

【问题讨论】:

    标签: r


    【解决方案1】:

    您可以在ungrouping 之前添加counts = sum(Enrollment) 摘要。

    library(tidyverse);
    df %>%
        group_by(grp = case_when(Coins < 20 ~ 'grp1', Coins ==20 ~ 'grp2', TRUE ~ 'grp3')) %>%
        group_by(grp) %>%
        summarise(
            Plan = toString(unique(Plan)),
            prop = n(),
            counts = sum(Enrollment)) %>%
        ungroup() %>%
        select(-grp);
    ## A tibble: 3 x 4
    #  Plan           prop counts
    #  <chr>         <int>  <int>
    #1 B, E, I           3    750
    #2 A, F, G, H, J     5   1900
    #3 C, D              2    400
    

    样本数据

    df <- read.table(text =
        "Plan    Year   Coins   Copay   Enrollment
      A     2018     20      10       200
      B     2014     15       5       100
      C     2012     30       0        50
      D     2017     30      10       350
      E     2018     5       10       400
      F     2018     20       0       150
      G     2018     20       0       200
      H     2016     20      10       800
      I     2014     10       3       250
      J     2017     20       7       550", header = T)
    

    【讨论】:

    • 是的!非常感谢 - 答案就在我面前(检查我的用户名)。还有一个问题:我目前得到的结果看起来像这样:6.33e5 - 我怎样才能返回一个准确的值?
    • @NewToThisRThing 我相信这就是tibble 在打印时格式化大量数字的方式;该值仍然是准确的。您可以在 magrittr 链的末尾添加 %&gt;% as.data.frame() 以“data.frame 方式”打印值。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-03-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多