我下面有数据框
year<-c(2016,2016,2016,2016)
city<-c("NY","NY","NY","NY")
spec<-c("df","df","vb","vb")
num<-c(45,67,89,90)
df<-data.frame(year,city,spec,num)
year city spec num
1 2016 NY df 45
2 2016 NY df 67
3 2016 NY vb 89
4 2016 NY vb 90
,我想按year
和city
分组,按spec
级别进行汇总,然后将spec
汇总转换为数据框列。像这样:
year city df vb
1 2016 NY 112 179
答案 0 :(得分:1)
使用dplyr
和tidyr
:
library(dplyr)
library(tidyr)
x <- df %>%
group_by(year, city, spec) %>%
summarise(num = sum(num)) %>%
spread(spec, num)
# Groups: year, city [1]
year city df vb
<dbl> <fct> <dbl> <dbl>
1 2016 NY 112 179