如何在表 DT1 中添加名為“ref”且值為“1”的列,對于表 DT2 中的現有行,使用 2 列(id1=id3 和 id2=id4)的連接?
DT1 <- data.table(
id1 = c('A','B','C', 'D'),
id2 = c(1,2,3,4)
)
DT2 <- data.table(
id3 = c('B','D','F'),
id4 = c(2,4,5)
)
DT1:
id1 id2
A 1,00000
B 2,00000
C 3,00000
D 4,00000
DT2:
id3 id4
B 2,00000
D 4,00000
預期結果:
id1 id2 ref
A 1,00000 0
B 2,00000 1
C 3,00000 0
D 4,00000 1
我從以下代碼開始,它沒有按我的意愿過濾:
result <- DT1[DT2, on = c(id1='id3', id2='id4')]
uj5u.com熱心網友回復:
添加一個帶有連接的新列,然后將 NA 轉換為零:
DT1[ DT2, on = c(id1 = 'id3', id2 = 'id4'), ref := 1 ][ is.na(ref), ref := 0 ]
DT1
# id1 id2 ref
# 1: A 1 0
# 2: B 2 1
# 3: C 3 0
# 4: D 4 1
uj5u.com熱心網友回復:
與%in%:
DT1[, ref := (id1 %in% DT2$id3)]
id1 id2 ref
1: A 1 0
2: B 2 1
3: C 3 0
4: D 4 1
用于paste多列:
DT1[, ref := (paste(id1, id2) %in% paste(DT2$id3, DT2$id4))]
uj5u.com熱心網友回復:
你可以加入這兩個data.table-merge
library(data.table)
#Add a new column `ref` in `DT2`.
DT2[, ref := 1]
#left join the two data.tables
result <- merge(DT1, DT2, by.x = c('id1', 'id2'),
by.y = c('id3', 'id4'), all.x = TRUE)
#Replace NAs with 0
result[is.na(ref), ref := 0]
result
# id1 id2 ref
#1: A 1 0
#2: B 2 1
#3: C 3 0
#4: D 4 1
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/529087.html
標籤:r数据表
下一篇:包含和替代
