使用group_by时创建汇总值并汇总

时间:2018-09-26 21:12:08

标签: r dplyr

我经常想显示给定基准年的变化。例如,自给定年份以来,发生了什么变化(百分比)? gapminder数据集提供了一个很好的示例:

change in population

要开始获得答案,您需要group_by年和大洲,然后summarize求和。但是,您如何获得一个汇总值,即1952年人口呢?

library(gapminder)
gapminder %>%
  group_by(year, continent) %>%
  summarize(tot_pop = sum(as.numeric(pop)),
            SUMMARY_VAL = POP_SUM_1952,
            CHG_SINCE_1952 = (tot_pop - SUMMARY_VAL ) / SUMMARY_VAL ) %>%
  ggplot(aes(x = year, y = CHG_SINCE_1952, color = continent)) +
  geom_line()

仅供参考,gapminder看起来像这样:

# A tibble: 1,704 x 6
   country     continent  year lifeExp      pop gdpPercap
   <fct>       <fct>     <int>   <dbl>    <int>     <dbl>
 1 Afghanistan Asia       1952    28.8  8425333      779.
 2 Afghanistan Asia       1957    30.3  9240934      821.
 3 Afghanistan Asia       1962    32.0 10267083      853.
 4 Afghanistan Asia       1967    34.0 11537966      836.
 5 Afghanistan Asia       1972    36.1 13079460      740.
 6 Afghanistan Asia       1977    38.4 14880372      786.
 7 Afghanistan Asia       1982    39.9 12881816      978.
 8 Afghanistan Asia       1987    40.8 13867957      852.
 9 Afghanistan Asia       1992    41.7 16317921      649.
10 Afghanistan Asia       1997    41.8 22227415      635.
# ... with 1,694 more rows

2 个答案:

答案 0 :(得分:2)

我正在尝试提出一个一步的解决方案。同时,这是一个简单的两步解决方案-

pop_1952 <- filter(gapminder, year == 1952) %>%
  group_by(continent) %>%
  summarise(tot_pop_1952 = sum(pop, na.rm = T))

gapminder %>%
  group_by(year, continent) %>%
  summarize(tot_pop = sum(as.numeric(pop))) %>%
  left_join(pop_1952, by = "continent") %>%
  mutate(
    CHG_SINCE_1952 = (tot_pop - tot_pop_1952) / tot_pop_1952
  ) %>%
  ggplot(aes(x = year, y = CHG_SINCE_1952, color = continent)) +
  geom_line()

如果有帮助的话,这里是一个解决方案(我认为从技术上讲还是两个步骤)-

gapminder %>%
  mutate(
    tot_pop_1952 = ave(as.numeric(pop)*(year == 1952), continent, FUN = sum)
  ) %>%
  group_by(year, continent) %>%
  summarize(
    tot_pop = sum(as.numeric(pop)),
    tot_pop_1952 = mean(tot_pop_1952),
    CHG_SINCE_1952 = (tot_pop - tot_pop_1952) / tot_pop_1952
  ) %>%
  ggplot(aes(x = year, y = CHG_SINCE_1952, color = continent)) +
  geom_line()

答案 1 :(得分:0)

使用dplyr的一步解决方案。

  gapminder %>%
    group_by(year, continent) %>%
    summarize(tot_pop = sum(as.numeric(pop))) %>%
    ungroup() %>% 
    mutate(CHG_POP = tot_pop - tot_pop[year == 1952]) %>% 
    ggplot(aes(x = year, y = tot_pop, color = continent)) +
    geom_line()