Age_Group Region Population
<fct> <fct> <int>
1 0-4 ENGLAND 3384925
2 5-9 ENGLAND 3497402
3 10-14 ENGLAND 3166038
4 15-19 ENGLAND 3120730
5 20-24 ENGLAND 3526141
6 25-29 ENGLAND 3831624
7 30-34 ENGLAND 3757400
8 35-39 ENGLAND 3642643
9 40-44 ENGLAND 3442758
10 45-49 ENGLAND 3850108嘿,伙计们,你们是否有最有效的方法来将年龄组按不同的间隔合并,比如5岁或10岁,形成下面的列表。
Age_Group Region Population
<fct> <fct> <int>
1 0-9 ENGLAND xxx
2 10-19 ENGLAND xxx
3 20-29 ENGLAND xxx
...发布于 2018-07-05 22:05:06
这里有一个tidyverse的可能性
library(tidyverse)
df %>%
mutate(grp = rep(1:(nrow(.)/2), each = 2)) %>%
group_by(grp) %>%
mutate(
Age_Group = paste(Age_Group, collapse = ":"),
Age_Group = gsub("-\\d+:\\d+", "", Age_Group)) %>%
mutate(Population = sum(Population)) %>%
slice(1) %>%
ungroup() %>%
select(-grp)
## A tibble: 5 x 3
# Age_Group Region Population
# <chr> <fct> <int>
#1 0-9 ENGLAND 6882327
#2 10-19 ENGLAND 6286768
#3 20-29 ENGLAND 7357765
#4 30-39 ENGLAND 7400043
#5 40-49 ENGLAND 7292866说明:正如@DavidArenburg所提到的,我们每隔两行对条目进行分组,通过将来自两行的Age_Group条目组合起来创建一个新的Age_Group标签,然后聚合Population条目。大部分工作来自创建新的Age_Group标签。
https://stackoverflow.com/questions/51200125
复制相似问题