【问题标题】:Is there a way to count occurrence within a group in R? [duplicate]有没有办法计算 R 中组内的发生率? [复制]
【发布时间】:2021-10-19 09:17:54
【问题描述】:

我有按县和村分组的人员名单。我想数一下各个县的村庄数量。我可以数出每个县的人数。

library(dplyr)

set.seed(123)

df <- data.frame(
  person = 1:100,
  county = round(runif(100, 1, 5)),
  village = round(runif(100, 1, 10))
)

# Number of people per county
df %>% count(county )

【问题讨论】:

  • df %&gt;% count(county, village)
  • tapply(df$village, df$county, FUN=function(x) length(unique(x)))

标签: r dplyr


【解决方案1】:

库(dplyr)

df %>% 
  group_by(county) %>% 
  add_count(village)

输出:

   person county village     n
    <int>  <dbl>   <dbl> <int>
 1      1      2       6     4
 2      2      4       4     8
 3      3      3       5     5
 4      4      5      10     1
 5      5      5       5     3
 6      6      1       9     2
 7      7      3       9     1
 8      8      5       6     2
 9      9      3       5     5
10     10      3       2     6
# ... with 90 more rows

【讨论】:

    【解决方案2】:

    这对你有用吗摩西

    df %>% group_by(county) %>% 
      count(village,county)
    

    【讨论】:

    • A 我看到你想按县统计每个村有多少人?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-14
    • 2015-09-06
    • 1970-01-01
    • 2021-12-15
    • 2020-10-04
    • 2020-07-30
    相关资源
    最近更新 更多