簡體   English   中英

根據條件將data.table列移至行

[英]Moving data.table columns to rows based on conditions

我有一個像這樣設置的大數據表:

ID Line.Rec Line.D.Amount Line.Desc Line1.Record Line1.D.Amount Line1.C.Amount Line2.Rec
1  1        100           test      2            500            200            3
2  1        200           testb     2            800            100            3
3  1        600           testc     2            900            500            NA

每個事件/行都包含一個ID和其他靜態列,例如Eventdate。 但是,線路數量不盡相同(可能從1到99)。 行還包含不同數量的列。 這些行不是固定的,某些文件的行與此行不同。 因此,我必須使用列名而不是位置。

我希望data.table看起來像這樣:

ID Record D.Amount C.Amount Description
1  1      100      0        test
1  2      500      200
1  3      0        0        
2  1      200               testb
2  2      800      100    
2  3      0        0  
3  1      600      0        testc
3  2      900      500      

解決方案需要確保與名稱的第一部分(line。,line1,.2,... line99。)匹配的任何列都包含在正確的行中。 如圖所示,需要包括ID行(和EventDate),以確保我可以跟蹤哪些行屬於同一行。

有任何想法嗎?

並不是真正的問題。 您可能需要考慮更改標簽。 這是應該讓您入門的內容:

library(data.table)
dt <- fread("ID Line.Rec Line.D.Amount Line.Desc Line1.Record Line1.D.Amount Line1.C.Amount Line2.Rec
1  1        100           test      2            500            200            3
2  1        200           testb     2            800            100            3
3  1        600           testc     2            900            500            NA")
#ensure that relevant columns share the same names
setnames(dt, gsub("Rec$", "Record", names(dt)))

#identify which columns forms a sub dataset
otherCols <- setdiff(names(dt), "ID")
groupCols <- split(otherCols, sapply(strsplit(otherCols, "\\."), `[`, 1))
newCols <- sapply(names(groupCols), 
    function(x) gsub(paste0(x, "."), "", groupCols[[x]]))

#take sub columns of original dataset by group    
subDataLs <- lapply(names(groupCols),
    function(x) setnames(dt[, c("ID", groupCols[[x]]), with=FALSE], 
        c("ID", newCols[[x]]))
)

#rbind sub datasets
output <- rbindlist(subDataLs, use.names=TRUE, fill=TRUE)

#format to desired output
cols <- names(output)[sapply(output, is.numeric)]
output[, (cols) := replace(.SD, is.na(.SD), 0), .SDcols=cols]
cols <- names(output)[sapply(output, is.character)]
output[, (cols) := replace(.SD, is.na(.SD), ""), .SDcols=cols]

輸出:

   ID Record D.Amount  Desc C.Amount
1:  1      1      100  test        0
2:  2      1      200 testb        0
3:  3      1      600 testc        0
4:  1      2      500            200
5:  2      2      800            100
6:  3      2      900            500
7:  1      3        0              0
8:  2      3        0              0
9:  3      0        0              0

暫無
暫無

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

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