12

我希望能够编写一个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
 }

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

#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
 }

谢谢

4

3 回答 3

7

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

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
于 2013-02-21T22:40:40.523 回答
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,")")))]})

}
于 2013-02-21T19:39:16.610 回答
0

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

 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> 

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

于 2013-02-21T19:01:15.500 回答