【问题标题】:How to sum values from multiple rows of a variable linked by household ID如何对由家庭 ID 链接的变量的多行值求和
【发布时间】:2020-05-10 07:54:53
【问题描述】:

我有以下 tibble(但实际上有更多行):它称为education_tibble

library(tidyverse)
education_tibble <- tibble(
   ghousecode = c(1011027, 1011017, 1011021, 1011019, 1011025, 1011017,
                  1011016, 1011021, 1011017, 1011019),
     hhc_educ = c(2, 0, 11, 10, 14, 4, 8, 16, 0, 9))


ghousecode hhc_educ
        <dbl>    <dbl>
 1    1011027        2
 2    1011017        0
 3    1011021       11
 4    1011019       10
 5    1011025       14
 6    1011017        4
 7    1011016        8
 8    1011021       16
 9    1011017        0
10    1011019        9

我正在尝试对 hhc_educ 求和,以便每个 ghousecode 都有相应的“总 hhc_edu”。我正在努力做到这一点,不知道该怎么做。我一直在使用 tidyverse,所以一直在探索主要在 dplyr 中的方法。这是我的代码:

education_tibble %>%
  group_by(ghousecode, add = TRUE) 
  summarize(total_educ = sum(hhc_educ))

问题是这段代码出于某种原因只生成一个值,而不是每个组的 total_edu 值。本质上,我最终追求的是一个新的 tibble,它将每个 ghousecode 放在一行中,旁边是所有 hhc_edu 值的总和。任何帮助将非常感激!谢谢!

【问题讨论】:

  • 可能你已经加载了plyr,它掩盖了summarize函数。试试dplyr::summarise

标签: r dplyr group-by tidyverse summarize


【解决方案1】:

我想你错过了%&gt;%

library(tidyverse)

#data
education_tibble <- tibble(
   ghousecode = c(1011027, 1011017, 1011021, 1011019, 1011025, 1011017,
                  1011016, 1011021, 1011017, 1011019),
     hhc_educ = c(2, 0, 11, 10, 14, 4, 8, 16, 0, 9))


# grouped count
education_tibble %>%
  group_by(ghousecode, add = TRUE)  %>% 
  summarise(total_educ = sum(hhc_educ))

生产:

# A tibble: 6 x 2
  ghousecode total_educ
       <dbl>      <dbl>
1    1011016          8
2    1011017          4
3    1011019         19
4    1011021         27
5    1011025         14
6    1011027          2

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-03-25
    • 1970-01-01
    • 2017-10-15
    • 2020-02-19
    • 1970-01-01
    • 2020-07-24
    • 1970-01-01
    相关资源
    最近更新 更多