Data.table和get()命令(R) [英] Data.table and get() command (R)

查看:324
本文介绍了Data.table和get()命令(R)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个问题,包括在一个函数中的 data.table 操作。输入参数是data.table名称和列/变量名称。

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

我可以使用 get 命令。但是,对变量名使用相同的命令不会工作。我知道 get()可能不适用于列/变量名称,但是我坚持使用哪个命令。

I can refer to the data.table by using the get() command. However, using the same command for the variable name doesn't work out. I know that get() might not be appropriate in case of the column/variable name, but I am stuck with which command to use.

EDITED:我现在已经包含 substitute(),而不是 get c $ c>,但仍然无法运作。

EDITED: I have now included substitute() instead of get() and it still doesn't work.

toy_example_fun <- function(d, .expr){

  .expr = substitute(.expr)

  setkey(get(d), .expr)  # ==> doesn't work

  d.agg <- get(d)[,list(sum(y), sum(v)), by=.expr]  # --> works
}

toy_example_fun("DT", x)

ALTERNATIVE: quote() - >这个工作。

ALTERNATIVE: quote() --> This works. However, I am interested in a solution that works inside a function.

DT <- data.table(x=rep(c("a","b","c"),each=3), y=c(1,3,6), v=1:9)    
d <- "DT"
variable <- quote(x)
d.agg <- get(d)[,list(sum(y), sum(v)), by=variable]  

即使后一种方法工作 variable< - quote(x)一个错误消息:

Even though, the latter alternative works variable <- quote(x) produces an error message:

  <simpleError in doTryCatch(return(expr), name, parentenv, handler): object 'x' not found>
    <simpleError in is.scalar(val): object 'x' not found>
    <simpleError in is.data.frame(obj): object 'x' not found> 

推荐答案


$ b解决方案

解决方案

这里:

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:


EDIT from Matthew :

+1以上。和/或字符列名也可以直接通过接受

+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

但是 someFun(DT,x)将不工作。因此,Adrie的回答比较笼统。

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

编辑 setkeyv / p>

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

这篇关于Data.table和get()命令(R)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆