Data.table and get() command (R)

前端 未结 1 1563
無奈伤痛
無奈伤痛 2021-01-06 13:07

I have a problem including a data.table operation in a function. Input arguments are the data.table name and the column/variable name.

I can refer to th

1条回答
  •  时光说笑
    2021-01-06 13:37

    Here you go:

    someFun <- function(d, .expr){
      group <- substitute(.expr)
      get(d)[,list(sum(y), sum(v)), by=group]
    }
    
    someFun("DT", x)
       group V1 V2
    1:     a 10  6
    2:     b 10 15
    3:     c 10 24
    
    
    someFun("DT", "x")
       x V1 V2
    1: a 10  6
    2: b 10 15
    3: c 10 24
    

    EDIT from Matthew :

    +1 to above. And/Or character column names are acceptable to by directly, too :

    someFun = function(d, col) {
        get(d)[,list(sum(y),sum(v)),by=col]
    }
    someFun("DT","x")
       x V1 V2
    1: a 10  6
    2: b 10 15
    3: c 10 24
    someFun("DT","x,y")
       x y V1 V2
    1: a 1  1  1
    2: a 3  3  2
    3: a 6  6  3
    4: b 1  1  4
    5: b 3  3  5
    6: b 6  6  6
    7: c 1  1  7
    8: c 3  3  8
    9: c 6  6  9
    

    but then someFun("DT",x) won't work. So Adrie's answer is more general.


    EDIT with setkeyv

    someFun <- function(d, cols){
      setkeyv(get(d), cols)
      cols <- substitute(cols)
      get(d)[,list(sum(y), sum(v)), by=cols]
    }
    
    someFun("DT", "x")
       x V1 V2
    1: a 10  6
    2: b 10 15
    3: c 10 24
    

    0 讨论(0)
提交回复
热议问题