【问题标题】:how to summarize one variable through group_by on another variable, so the output variable is connected to grouped variable如何通过group_by对另一个变量进行汇总,使输出变量连接到分组变量
【发布时间】:2023-02-10 15:57:28
【问题描述】:

我试图通过对一个变量进行分组来总结一个变量的计数,以便 total_count 连接到分组变量的每一行。

我希望能够通过对 fam_id 进行分组来添加“emp”列,以便 total_employed 反映同一 fam_id 中所有人的家庭就业人数

acs_5years

fam_id  emp  ins  age
33      1    1    45
33      0    1    23
44      1    1    19
44      1    0    26
44      1    0    54
44      0    0    50
77      1    1    33
77      1    1    38
77      1    1    44
88      1    0    65
88      0    0    90

应该看起来像:

fam_id  emp  ins  age  total_employed
33      1    1    45     1
33      0    1    23     1
44      1    1    19     4
44      1    0    26     4
44      1    0    54     4
44      1    0    50     4
77      1    1    33     3
77      1    1    38     3
77      1    1    44     3
88      1    0    65     1
88      0    0    90     1

我试过以下代码:

sample_grouping <- acs_5years %>% group_by(SERIAL) %>%
  summarize(total_count=n(),.groups = 'drop') %>%
  as.data.frame()

sample_grouping

#######

sample_2 <- acs_5years %>% group_by(SERIAL) %>%
  summarize(total_count=(emp))

sample_2

我不确定我得到的结果是否正确。

任何帮助或建议将不胜感激,在此先感谢!

【问题讨论】:

    标签: r dplyr group-by


    【解决方案1】:

    empfam_id44不一样,你的代码和你的数据不一样,你可以试试

    df %>%
      group_by(fam_id) %>%
      mutate(total_employed = sum(emp))
    
       fam_id   emp   ins   age total_employed
        <int> <int> <int> <int>          <int>
     1     33     1     1    45              1
     2     33     0     1    23              1
     3     44     1     1    19              3
     4     44     1     0    26              3
     5     44     1     0    54              3
     6     44     0     0    50              3
     7     77     1     1    33              3
     8     77     1     1    38              3
     9     77     1     1    44              3
    10     88     1     0    65              1
    11     88     0     0    90              1
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-07-16
      • 2021-09-26
      • 2019-08-18
      • 1970-01-01
      • 2023-04-01
      相关资源
      最近更新 更多