首页 > 解决方案 > 汇总行值并创建新类别

问题描述

我正在使用人口数据框,我有不同年份和年龄组的信息,除以五年的箱子。一旦我过滤了我感兴趣的位置的信息,我就有了:

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”的总和

我尝试选择带有数字的列,这样我就可以添加每个年龄组的总数并使用新的年龄组创建一行,但我无法以简单的方式添加行,而且我让事情变得更加复杂。我确信有一种简单的方法可以解决这个问题,但我被卡住了。

标签: rsumaggregation

解决方案


请参阅下面的我的答案:

我的第一行读取了显示的数据。

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

推荐阅读