r - data.table join and then add all columns from one table to another

前端 未结 1 729
半阙折子戏
半阙折子戏 2021-01-03 07:34

My question is essentially the same as this question: data.table join then add columns to existing data.frame without re-copy.

Basically I have a template with keys

相关标签:
1条回答
  • 2021-01-03 07:54

    Just create a function that takes names as arguments and constructs the expression for you. And then eval it each time by passing the names of each data.table you require. Here's an illustration:

    get_expr <- function(x) {
        # 'x' is the names vector
        expr = paste0("i.", x)
        expr = lapply(expr, as.name)
        setattr(expr, 'names', x)
        as.call(c(quote(`:=`), expr))
    }
    
    > get_expr('value')    ## generates the required expression
    # `:=`(value = i.value)
    
    template[x, eval(get_expr("value"))]
    template[y, eval(get_expr("value"))]
    
    #     id1 id2       value
    #  1:   a   1          NA
    #  2:   a   2  0.01649728
    #  3:   a   3 -0.27918482
    #  4:   a   4 -1.16343900
    #  5:   a   5          NA
    #  6:   b   1          NA
    #  7:   b   2          NA
    #  8:   b   3  0.86933718
    #  9:   b   4  2.26787200
    # 10:   b   5  1.08325800
    
    0 讨论(0)
提交回复
热议问题