使用来自多行的 data.table 在 R 中重塑

Reshaping in R using data.table from multiple rows

虽然 Stackoverlow 上有很多关于在 R 中重塑数据的帖子,但我似乎找不到一篇解释如何处理我的情况的帖子。

我有一个形状像这样的数据集,如果 id 与类型 1,2 或 3 相关,则每行代表一个二进制文件。

data <- data.table( id    = c(1,1,1,2,2,2,3,3,3),
                    type1 = c(1,0,0,0,0,1,0,0,0), 
                    type2 = c(0,1,0,0,1,0,1,0,0), 
                    type3 = c(0,0,1,0,0,0,0,1,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,1,2,2,2,3,3,3),
                    type1 = c(1,0,0,0,0,1,0,0,0), 
                    type2 = c(0,1,0,0,1,0,1,0,0), 
                    type3 = c(0,0,1,0,0,0,0,1,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-02-11

你可以总结一下:

data1 <- data[,.(type1 = sum(type1),
                 type2 = sum(type2),
                 type3 = sum(type3)
                 ), by = id]