0

我正在努力为我在 R 中使用生存库时不断遇到的环境问题找到一个优雅的解决方案。这是我遇到的问题的一个玩具示例:

# Make a fake data set
set.seed(1)
BigData <- cbind(rexp(100, .3), rbinom(100, 1, .7), 
             matrix(rnorm(300), ncol = 3)) %>% data.frame
names(BigData) <- c('time','event', 'var1', 'var2', 'var3')

# Make n function for fitting the model (myFitFunction).
# I am allowed to edit this function.
myFitFunction <- function(origdata, formula, ...){
  fit <- coxph(formula, data = origdata, ...)
  return(fit)
}
# There exists a function for fitting the 
# same model with new data (otherFitFunction).
# For the purposes of this example, say I cannot edit this one.
otherFitFunction <- function(object, newdata){
  survfit(object, newdata=newdata)
}
myMod <- myFitFunction(BigData[1:75,], 
        as.formula(Surv(time, event) ~ var1+var2+var3))
otherFitFunction(myMod, BigData[76:100,])

这给了我错误信息:

“is.data.frame(data) 中的错误:找不到对象‘origdata’调用:otherFitFunction ... -> model.frame.default -> is.data.frame”

我知道这是一个常见问题,尤其是在进行交叉验证时,并且有一些解决方案,例如在以下位置找到的解决方案: in R: Error in is.data.frame(data) : object '' not found, C5. 0情节。(更具体地说,我知道这个例子中的问题来自生存包中“survfit.coxph.R”文件中~55行的stats::model.frame()代码。)通过阅读stackexchange上的其他帖子,我找到解决我的问题的方法,即将 myFitFunction() 调整为:

myFitFunction <- function(origdata, formula, ...){
  myenv$origdata <- origdata
  fit <- coxph(formula, data = origdata, ...)
  environment(fit$formula) <- myenv
  fit$terms <- terms(fit$formula)

  return(fit)
}

但是,我看到或使用过的所有代码似乎都非常 hacky(包括我的,这需要我每次都保存原始数据)。此外,在我的真实代码中,我实际上无法编辑 otherFitFunction(),只能编辑甚至直接访问 myFitFunction(),这限制了我使用其他人使用的某些解决方案的能力。

我想知道这个问题是否有更优雅的解决方案。我试过玩 pryr 包,但似乎想不出任何有用的东西。

任何帮助将非常感激。

4

1 回答 1

1

怎么样

myFitFunction <- function(origdata, formula, ...){
  environment(formula) <- environment()
  fit <- coxph(formula, data = origdata, ...)
  return(fit)
}

由于公式可以捕获环境,因此您只需要捕获origdata定义的环境。

另一种方法是调整调用myFitFunction以使用原始变量运行父框架中的所有内容。例如

myFitFunction <- function(origdata, formula, ...){
  call <- match.call()
  call$formula <- formula
  call$data <- call$origdata
  call$origdata <- NULL
  call[[1]] <- quote(coxph)
  fit <- eval.parent(call)
  return(fit)
}
于 2018-02-16T20:53:41.480 回答