问题描述
虽然 Stackoverlow 上有很多关于在 R 中重塑数据的帖子,但我似乎找不到解释如何处理我的情况的帖子。
我有一个这样形状的数据集,如果 id 与类型 1,2 或 3 相关,则每行表示包含一个二进制文件。
data <- data.table( id = c(1,1,2,3,3),type1 = c(1,0),type2 = c(0,type3 = c(0,0))
> data
id type1 type2 type3
1: 1 1 0 0
2: 1 0 1 0
3: 1 0 0 1
4: 2 0 0 0
5: 2 0 1 0
6: 2 1 0 0
7: 3 0 1 0
8: 3 0 0 1
9: 3 0 0 0
但是,我希望将此信息包含在每个 id 值的一行中。
> data
id type1 type2 type3
1: 1 1 1 1
2: 2 1 1 0
3: 3 0 1 1
如何使用 data.table
解决此问题?
解决方法
library(data.table)
data <- data.table( id = c(1,1,2,3,3),type1 = c(1,0),type2 = c(0,type3 = c(0,0))
vars <- grep("^type",names(data),value = T)
data[,lapply(.SD,sum),.SDcols = vars,by = id]
#> id type1 type2 type3
#> 1: 1 1 1 1
#> 2: 2 1 1 0
#> 3: 3 0 1 1
由 reprex package (v1.0.0) 于 2021 年 2 月 11 日创建
,你可以做一个总结:
data1 <- data[,.(type1 = sum(type1),type2 = sum(type2),type3 = sum(type3)
),by = id]