与多个性别特有年龄段的人口数据旋转
我有以下人口结构:
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
)
# A tibble: 2 x 6
female female_population male male_population total total_population
<chr> <dbl> <chr> <dbl> <chr> <dbl>
1 0-10 30000 0-10 33000 0-10 63000
2 10-20 50000 10-20 45000 10-20 95000
我想对其进行旋转,以便我为这样的年龄,性别和人口提供一栏:
tibble(
sex = rep(c("female", "male", "total"), each = 2),
age = rep(c("0-10", "10-20"), 3),
population = c(30000, 50000, 33000, 45000, 63000, 95000)
)
# A tibble: 6 x 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
有什么想法优雅地做,也许使用pivot_longer?
I have the following population structure:
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
)
# A tibble: 2 x 6
female female_population male male_population total total_population
<chr> <dbl> <chr> <dbl> <chr> <dbl>
1 0-10 30000 0-10 33000 0-10 63000
2 10-20 50000 10-20 45000 10-20 95000
I'd like to pivot it so that I get a single column for age, sex and population like this:
tibble(
sex = rep(c("female", "male", "total"), each = 2),
age = rep(c("0-10", "10-20"), 3),
population = c(30000, 50000, 33000, 45000, 63000, 95000)
)
# A tibble: 6 x 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
Any ideas how to do that elegantly, maybe using pivot_longer?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
尝试使用
Pivot_longer
:(可以使用
%&gt;%
而不是|&gt;
;后者在基本R的最新版本中。>
Try this using
pivot_longer
:(
%>%
may be used instead of|>
; the latter is in more recent versions of base R.)Created on 2022-07-02 by the reprex package (v2.0.1)