pivot_longer
:
(
%>%
可用于代替
|>
; 后者出现在base R的最新版本中。)
library(tidyverse)
df <- tibble(
female = c("0-10", "10-20"),
female_population = c(30000, 50000),
male = c("0-10", "10-20"),
male_population = c(33000, 45000),
total = c("0-10", "10-20"),
total_population = female_population + male_population
)
df |>
pivot_longer(!contains("_"), names_to = "sex", values_to = "age") |>
mutate(population = case_when(
sex == "female" ~ female_population,
sex == "male" ~ male_population,
sex == "total" ~ total_population
)) |>
select(-contains("_")) |>
arrange(sex)
#> # A tibble: 6 Ã 3
#> sex age population
#> <chr> <chr> <dbl>
#> 1 female 0-10 30000
#> 2 female 10-20 50000
#> 3 male 0-10 33000
#> 4 male 10-20 45000
#> 5 total 0-10 63000
#> 6 total 10-20 95000
于2022年7月2日由
reprex package
(v2.0.1)