【问题标题】:Count Observations Meeting Certain Criteria by Group R按 R 组计算符合某些标准的观察值
【发布时间】:2021-11-10 20:19:50
【问题描述】:

我需要一些帮助来按组计算符合特定标准的观察结果。我首先想要按位置的员工人数作为一列。然后我想检索工作超过 40 小时(按位置)的员工数量,并将其汇总到一个列中。我认为有一种简单的方法可以使用 dplyr 或 base R 来做到这一点,但我很难过。我的数据如下。

name       hours_worked  location
Bob        55            IL
Nick       25            IL 
Sally      30            IL
Patricia   50            WI
Tim        35            WI
Liz        42            OH
Brad       60            OH
Sam        48            OH

理想的输出应该是这样的:

location   headcount   over_40 
IL            3          1
WI            2          1
OH            3          3

【问题讨论】:

    标签: r dplyr data-manipulation


    【解决方案1】:

    我们可以按操作进行分组 - 按“位置”分组得到行数 (n()) 的人数和逻辑向量的sum 得到“over_40”的计数

    library(dplyr)
    df1 %>% 
       group_by(location) %>% 
       summarise(headcount = n(), over_40 = sum(hours_worked > 40))
    

    -输出

    # A tibble: 3 x 3
      location headcount over_40
      <chr>        <int>   <int>
    1 IL               3       1
    2 OH               3       3
    3 WI               2       1
    

    数据

    df1 <- structure(list(name = c("Bob", "Nick", "Sally", "Patricia", "Tim", 
    "Liz", "Brad", "Sam"), hours_worked = c(55L, 25L, 30L, 50L, 35L, 
    42L, 60L, 48L), location = c("IL", "IL", "IL", "WI", "WI", "OH", 
    "OH", "OH")), class = "data.frame", row.names = c(NA, -8L))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多