以编程方式将列名称传递给data.table

时间:2013-02-21 18:28:23

标签: r data.table

我希望能够编写一个按组data.table运行回归的函数,然后很好地组织结果。以下是我想要做的一个示例:

require(data.table)
dtb = data.table(y=1:10, x=10:1, z=sample(1:10), weights=1:10, thedate=1:2)
models = c("y ~ x", "y ~ z")

res = lapply(models, function(f) {dtb[,as.list(coef(lm(f, weights=weights, data=.SD))),by=thedate]})

#do more stuff with res

我想将所有这些包装成一个函数,因为#doe more stuff可能很长。我面临的问题是如何将各种名称传递给data.table?例如,如何传递列名weights?我如何通过thedate?我想象一个看起来像这样的原型:

myfun = function(dtb, models, weights, dates)

让我说清楚:将公式传递给我的函数不是问题。如果我想使用的weights和描述日期的列名,thedate已知,那么我的函数可能看起来像这样:

 myfun = function(dtb, models) {
res = lapply(models, function(f) {dtb[,as.list(coef(lm(f, weights=weights, data=.SD))),by=thedate]})

 #do more stuff with res
 }

但是,与thedateweights对应的列名称事先未知。我想将它们传递给我的函数:

#this will not work
myfun = function(dtb, models, w, d) {
res = lapply(models, function(f) {dtb[,as.list(coef(lm(f, weights=w, data=.SD))),by=d]})

 #do more stuff with res
 }

由于

3 个答案:

答案 0 :(得分:5)

这是一个依赖于长格式数据的解决方案(这对我来说更有意义,在这个cas

library(reshape2)
dtlong <- data.table(melt(dtb, measure.var = c('x','z')))


foo <- function(f, d, by, w ){
  # get the name of the w argument (weights)
  w.char <- deparse(substitute(w))
  # convert `list(a,b)` to `c('a','b')`
  # obviously, this would have to change depending on how `by` was defined
  by <- unlist(lapply(as.list(as.list(match.call())[['by']])[-1], as.character))
  # create the call substituting the names as required
  .c <- substitute(as.list(coef(lm(f, data = .SD, weights = w), list(w = as.name(w.char)))))
  # actually perform the calculations
  d[,eval(.c), by = by]
}

foo(f= y~value, d= dtlong, by = list(variable, thedate), w = weights)

   variable thedate (Intercept)       value
1:        x       1   11.000000 -1.00000000
2:        x       2   11.000000 -1.00000000
3:        z       1    1.009595  0.89019190
4:        z       2    7.538462 -0.03846154

答案 1 :(得分:3)

一种可能的解决方案:

fun = function(dtb, models, w_col_name, date_name) {
     res = lapply(models, function(f) {dtb[,as.list(coef(lm(f, weights=eval(parse(text=w_col_name)), data=.SD))),by=eval(parse(text=paste0("list(",date_name,")")))]})

}

答案 2 :(得分:1)

你不能只添加(在匿名函数调用内):

 f <- as.formula(f) 

...作为dtb[,as.list(coef(lm(f, ...)之前的单独一行?这是将字符元素转换为公式对象的常用方法。

> res = lapply(models, function(f) {f <- as.formula(f)
                 dtb[,as.list(coef(lm(f, weights=weights, data=.SD))),by=thedate]})
> 
> str(res)
List of 2
 $ :Classes ‘data.table’ and 'data.frame':  2 obs. of  3 variables:
  ..$ thedate    : int [1:2] 1 2
  ..$ (Intercept): num [1:2] 11 11
  ..$ x          : num [1:2] -1 -1
  ..- attr(*, ".internal.selfref")=<externalptr> 
 $ :Classes ‘data.table’ and 'data.frame':  2 obs. of  3 variables:
  ..$ thedate    : int [1:2] 1 2
  ..$ (Intercept): num [1:2] 6.27 11.7
  ..$ z          : num [1:2] 0.0633 -0.7995
  ..- attr(*, ".internal.selfref")=<externalptr> 

如果您需要从组件名称构建公式的字符版本,只需使用pastepaste0并传递给模型字符向量。提供经测试的代码,并提供可测试示例。