r - 汇总行值并创建新类别
问题描述
我正在使用人口数据框,我有不同年份和年龄组的信息,除以五年的箱子。一旦我过滤了我感兴趣的位置的信息,我就有了:
Location age group total90 total95 total00 total05 total10
A 0 to 4 10428 118902 76758 967938 205472
A 5 to 9 18530 238928 260331 277635 303180
A 10 to 14 180428 208902 226758 267938 305472
A 15 to 19 185003 332089 242267 261793 135472
现在我想要的是创建新的年龄组来拥有这样的东西:
Location age group total90 total95 total00 total05 total10
A 5 to 14 198958 447830 487089 545573 608652
A other 195431 450991 319025 1229731 340944
在哪里
年龄组“5 到 14”是每年“5 到 9”+“10 到 14”的总和 &
“其他”是每年“0到4”+“15到19”的总和
我尝试选择带有数字的列,这样我就可以添加每个年龄组的总数并使用新的年龄组创建一行,但我无法以简单的方式添加行,而且我让事情变得更加复杂。我确信有一种简单的方法可以解决这个问题,但我被卡住了。
解决方案
请参阅下面的我的答案:
我的第一行读取了显示的数据。
library(tidyverse)
#read in data
my_data <- read_csv("pop_data.csv")
#add extra tags
my_data1 <- my_data %>%
mutate(Category = c("other","5 to 14","5 to 14","other")) %>%
select(-`age group`)
#find numeric columns
numeric_col <- unlist(lapply(my_data1, is.numeric))
#combine the data
my_data2 <- aggregate(my_data1[,numeric_col],
by = list(my_data1$Location, my_data1$Category),
FUN = sum)
#rename first 2 columns
colnames(my_data2)[1:2] <- c("Location", "age group")
结果:
Location age group total90 total95 total00 total05 total10
1 A 5 to 14 198958 447830 487089 545573 608652
2 A other 195431 450991 319025 1229731 340944
推荐阅读
- android - 为什么键盘会覆盖 EditText 的一部分
- linux - 如何在 codedeploy 脚本的帮助下将 AWS 凭证传递给 EC2 服务器?
- wordpress - 如何在 WordPress 项目中使用 Nuxt.js 组件?
- spring-boot - 通过 Elasticsearch REST 客户端对文档进行索引时引发错误
- python - django charField 只接受数字
- asp.net-core - 如何对 .NET Core 3.1 中使用 ExecuteSqlRawAsync 调用存储过程的函数进行单元测试?
- firebase - 设备文本识别
- javascript - 传单:如何移动多边形
- java - 我想在不使用 WEBSOCKETS IN JAVA 的情况下构建将客户端传递到服务器的实时数据
- apache-kafka - Kafka Streams K-Table 大小监控