[英]Aggregate over combinations of columns with data.table
Suppose I have this data假设我有这些数据
> dput(data)
structure(list(Country = c("USA", "USA", "USA", "USA", "USA",
"USA", "USA", "USA", "USA"), Location = c("West", "East", "East",
"North", "North", "East", "West", "North", "East"), Gender = c("M",
"M", "F", "F", "F", "F", "F", "F", "M"), Age = c("20 - 30", "30 - 40",
"20 - 30", "30 - 40", "20 - 30", "20 - 30", "30 - 40", "20 - 30",
"30 - 40"), Civil_Status = c("Single", "Single", "Married", "Married",
"Married", "Single", "Single", "Married", "Married"), Expenditure = c(320,
400, 800, 900, 750, 350, 620, 1200, 800)), row.names = c(NA,
-9L), class = c("tbl_df", "tbl", "data.frame"))
Country Location Gender Age Civil_Status Expenditure
<chr> <chr> <chr> <chr> <chr> <dbl>
1 USA West M 20 - 30 Single 320
2 USA East M 30 - 40 Single 400
3 USA East F 20 - 30 Married 800
4 USA North F 30 - 40 Married 900
5 USA North F 20 - 30 Married 750
6 USA East F 20 - 30 Single 350
7 USA West F 30 - 40 Single 620
8 USA North F 20 - 30 Married 1200
9 USA East M 30 - 40 Married 800
What I'm trying to do is sum the expenditure over all the combinations of the variables gender, age, civil_status, first by Country and later for all the possible locations and then merge all this combinations of results into a single dataset.我要做的是对变量性别、年龄、公民身份的所有组合的支出求和,首先是国家,然后是所有可能的位置,然后将所有这些结果组合合并到一个数据集中。
Here's an example这是一个例子
Usa
USA, Gender
USA, Age
USA, Civil_Status
USA, Gender, Age
USA, Gender, Civil_Status
.....................
West, Gender
West, Age
.....................
In this case I will have 2^3=8 combinations for Country and 8 combinations for each one of the locations.在这种情况下,我将有 2^3=8 个 Country 组合和每个位置 8 个组合。
One option is rollup
from data.table
一种选择是从
data.table
rollup
library(data.table)
setDT(data)
rollup(data, j = sum(Expenditure), by = c("Country","Gender","Age", "Civil_Status"))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.