在 R 中聚合 data.frame 中的轴
Aggregate an axis in data.frame in R
考虑以下数据:
df <- data.frame(sex = c("MALE","FEMALE","MALE","FEMALE"),
time = c("2018","2018","2019","2019"),
country = c("USA","USA","USA","USA"),
value = c(10,10,10,10))
如何聚合“性别”轴,所以我得到以下数据:
TIME Country Value
1 2018 USA 20
2 2019 USA 20
我如何在 R 中做到这一点(我知道这可能是一个简单的问题)?
使用 dplyr
,执行以下操作:
df %>% group_by(time, country)%>% summarize(sumval = sum(value))
# A tibble: 2 x 3
# Groups: time [2]
time country sumval
<chr> <chr> <dbl>
1 2018 USA 20
2 2019 USA 20
考虑以下数据:
df <- data.frame(sex = c("MALE","FEMALE","MALE","FEMALE"),
time = c("2018","2018","2019","2019"),
country = c("USA","USA","USA","USA"),
value = c(10,10,10,10))
如何聚合“性别”轴,所以我得到以下数据:
TIME Country Value
1 2018 USA 20
2 2019 USA 20
我如何在 R 中做到这一点(我知道这可能是一个简单的问题)?
使用 dplyr
,执行以下操作:
df %>% group_by(time, country)%>% summarize(sumval = sum(value))
# A tibble: 2 x 3
# Groups: time [2]
time country sumval
<chr> <chr> <dbl>
1 2018 USA 20
2 2019 USA 20