data.table: Proper way to do create a conditional variable when column names are not known?

前端 未结 2 1564
别跟我提以往
别跟我提以往 2020-12-24 15:19

My question relates to the creation of a variable which depends upon other columns within a data.table when none of the variable names are known in advance.

Below is

相关标签:
2条回答
  • 2020-12-24 15:26

    1. get/if Try using get :

    DT[, (Col4) := if (get(Col1) == "A") get(Col2) else get(Col3), by = 1:nrow(DT)]
    

    2. get/join or try this approach:

    setkeyv(DT, Col1)
    DT[, (Col4):=get(Col3)]["A", (Col4):=get(Col2)]
    

    3. .SDCols or this:

    setkeyv(DT, Col1)
    DT[, (Col4):=.SD, .SDcols = Col3]["A", (Col4):=.SD, .SDcols = Col2]
    

    UPDATE: Added some additional approaches.

    0 讨论(0)
  • 2020-12-24 15:48

    Using ifelse and get:

    DT[, (Col4) := ifelse (get(Col1) == "A",get(Col2) , get(Col3))]
    

    Or using substitute to create the expression like this :

    expr <- substitute(a4 := ifelse (a1 == "A",a2 , a3),
                       list(a1=as.name(Col1),
                            a2=as.name(Col2),
                            a3=as.name(Col3),
                            a4=as.name(Col4)))
    
    DT[, eval(expr)]
    
    0 讨论(0)
提交回复
热议问题