簡體   English   中英

合並列名上的 2、1 行 data.tables

[英]Merging 2, 1 row data.tables on column names

我有 2、1 行 data.tables。

dt1 <- data.table(a = 0, b = 0, c = 0)
dt2 <- data.table(a = 1, c = 5)

我的目標是用dt2的值更新dt1以便我得到:

desired_dt <- data.table(a = 1, b = 0, c = 5) 

我嘗試合並,假設它與共享列名匹配,但沒有運氣。

dt2[dt1]
Error in `[.data.table`(dt2, dt1) : 
When i is a data.table (or character vector), the columns to join by must be specified using 'on=' 
argument (see ?data.table), by keying x (i.e. sorted, and, marked as sorted, see ?setkey), or by 
sharing column names between x and i (i.e., a natural join). Keyed joins might have further speed 
benefits on very large data due to x being sorted in RAM.

這不被認為是自然加入嗎? 對於我所缺少的東西,我將不勝感激!

我們得到intersect的列名並進行賦值

nm1 <- intersect(names(dt1), names(dt2))
dt1[, (nm1) := dt2]

或者我們可以set密鑰

setkeyv(dt1, intersect(names(dt1), names(dt2)))
out <- dt1[dt2]
for(j in seq_along(out)) set(out, i = which(is.na(out[[j]])), j=j, value = 0)

這是使用rbindlist + fcoalescedata.table選項

setcolorder(
  rbindlist(
    list(dt2, dt1),
    fill = TRUE
  )[
    ,
    lapply(.SD, function(x) fcoalesce(as.list(x)))
  ], names(dt1)
)[]

這使

   a b c
1: 1 0 5

暫無
暫無

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

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