我正在尝试编写包装基本 gamlss 建模的函数(因为我正在准备一个更高级别的、特定于应用程序的包)。但我遇到了包装预测的问题。
predict.gamlss
文档中的示例效果很好:
suppressMessages(library(gamlss))
data(aids)
a<-gamlss(y~poly(x,3)+qrt, family=PO, data=aids)
#> GAMLSS-RS iteration 1: Global Deviance = 416.8014
#> GAMLSS-RS iteration 2: Global Deviance = 416.8014
newaids<-data.frame(x=c(45,46,47), qrt=c(2,3,4))
predict(a, newdata = newaids)
#> Warning in predict.gamlss(a, newdata = newaids): There is a discrepancy between the original and the re-fit
#> used to achieve 'safe' predictions
#>
#> [1] 6.021313 6.232357 6.155965
但是一旦我包装它,代码就失败了:
gamlss_fit <- function(input) {
gamlss(y~poly(x,3)+qrt, family=PO, data=input)
}
gamlss_predict <- function(fit, input) {
predict(fit, newdata = input)
}
fit <- gamlss_fit(aids)
#> GAMLSS-RS iteration 1: Global Deviance = 416.8014
#> GAMLSS-RS iteration 2: Global Deviance = 416.8014
gamlss_predict(fit, newaids)
#> Error in eval(Call$data): object 'input' not found
我隐约怀疑管理假定的
environment
存在问题。我尝试查看 predict.gamlss
的 implementation,但我无法遵循它。该问题似乎与问题 here 有关,但原始
newdata
调用适用于我的情况。如果有任何建议,我将不胜感激。
我能够通过将输入数据集添加到函数内的全局环境来解决相同的问题。尝试:
gamlss_predict <- function(fit, input) {
input <<- input
predict(fit, newdata = input)
rm(input)
}