簡體   English   中英

使用 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

代表 package (v1.0.0) 於 2021 年 2 月 11 日創建

你可以做一個總結:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM