You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在纯dplyr/tidyverse环境中计算各洲人口相对于1952年的增长率?

Answer

Absolutely, you can do this entirely within the tidyverse/dplyr ecosystem! Here are two clean approaches to get population growth rates relative to 1952:

Approach 1: Calculate growth rates in long format first

This method computes relative growth while your data is still in long format (flexible for further analysis), then spreads to wide format:

library(tidyverse)

gapminder <- readr::read_csv("https://raw.githubusercontent.com/OHI-Science/data-science-training/master/data/gapminder.csv")

gapminder %>% 
  # Get total population per continent and year
  group_by(continent, year) %>% 
  summarize(cont_pop = sum(pop), .groups = "drop") %>%
  # For each continent, grab the 1952 population as our reference
  group_by(continent) %>%
  mutate(
    ref_pop_1952 = cont_pop[year == 1952],
    # Calculate growth rate: (current year pop / 1952 pop) - 1 (decimal)
    growth_rate_rel_1952 = (cont_pop / ref_pop_1952) - 1,
    # Optional: Convert to percentage instead of decimal
    # growth_rate_pct = ((cont_pop / ref_pop_1952) - 1) * 100
  ) %>%
  ungroup() %>%
  # Keep only columns needed for wide format
  select(continent, year, growth_rate_rel_1952) %>%
  # Spread to wide format with years as columns
  spread(year, value = growth_rate_rel_1952)

Approach 2: Spread first, then compute growth rates

If you prefer to work with wide format immediately, spread the absolute population values first, then use across() to apply the growth calculation to all year columns:

gapminder %>% 
  group_by(continent, year) %>% 
  summarize(cont_pop = sum(pop), .groups = "drop") %>%
  # Spread to wide format with absolute populations
  spread(year, value = cont_pop) %>%
  # Calculate growth rate relative to 1952 for all year columns
  mutate(
    across(-continent, ~ (. / `1952`) - 1),
    # Optional: For percentage instead of decimal
    # across(-continent, ~ ((. / `1952`) - 1) * 100)
  )

Key Notes:

  • Both methods return growth rates relative to 1952 (e.g., a value of 0.5 equals 50% growth since 1952).
  • Use the optional percentage line if you want results formatted as percentages rather than decimals.
  • The across() function in Approach 2 avoids manually listing every year column, making the code concise and scalable.

内容的提问来源于stack exchange,提问作者ECII

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.30 16:44:08