R data table: update join

后端 未结 2 1506
伪装坚强ぢ
伪装坚强ぢ 2021-01-03 08:24

Suppose I have two data tables:

X <- data.table(id = 1:5, L = letters[1:5])

   id L
1:  1 a
2:  2 b
3:  3 c
4:  4 d
5:  5 e

Y <- data.table(id = 3:5,         


        
2条回答
  •  萌比男神i
    2021-01-03 08:59

    It is an update join:

    library(data.table)
    X <- data.table(id = 1:5, L = letters[1:5])
    Y <- data.table(id = 3:5, L = c(NA, "g", "h"), N = c(10, NA, 12))
    X[Y, on=.(id), c("L", "N"):=.(i.L, i.N)][]
    #    id  L  N
    # 1:  1  a NA
    # 2:  2  b NA
    # 3:  3 NA 10
    # 4:  4  g NA
    # 5:  5  h 12
    

    gives you the desired result.
    Here I found a solution for multiple columns:

    library(data.table)
    X <- data.table(id = 1:5, L = letters[1:5])
    Y <- data.table(id = 3:5, L = c(NA, "g", "h"), N = c(10, NA, 12))
    
    X[Y, on=.(id), names(Y)[-1]:=mget(paste0("i.", names(Y)[-1]))]
    

    Another variant:

    n <- names(Y)
    X[Y, on=.(id), (n):=mget(paste0("i.", n))]
    

提交回复
热议问题