在下面的示例中,我使用包装函数来拟合gls对象。我可以成功返回原始数据的模型预测,但不能在使用newdata
时返回错误“Error in eval(expr, envir, enclos) : 'nthcdr' needs a list to CDR down
”:
# library -----------------------------------------------------------------
library(nlme)
# wrapper function --------------------------------------------------------
test.gls <- function(data, ...){
fit <- gls(data=data, ...)
return(fit)
}
# make data ---------------------------------------------------------------
set.seed(1)
n <- 20
x <- sort(rlnorm(n, meanlog = 0.25, sdlog = 1.5))
b <- 100
cv <- 0.5
y <- x*b * rlnorm(n, 0, cv)
dat <- data.frame(x,y)
# fit model ---------------------------------------------------------------
fit <- test.gls(data=dat, model=y~x-1, weights=varExp())
class(fit)
# [1] "gls"
plot(y~x, dat)
lines(dat$x, predict(fit)) # works
# prediction --------------------------------------------------------------
newdat <- data.frame(x=sort(rlnorm(n, meanlog = 0.25, sdlog = 1.5)))
pred <- predict(fit)
newpred <- predict(fit, newdata = newdat)
# Error in eval(expr, envir, enclos) : 'nthcdr' needs a list to CDR down
答案 0 :(得分:2)
以下答案似乎使用do.call
提供了一个解决方案:https://stackoverflow.com/a/7668846/1199289
示例:
# library -----------------------------------------------------------------
library(nlme)
# wrapper function --------------------------------------------------------
test.gls <- function(data, ...){
fit <- gls(data=data, ...)
return(fit)
}
test.gls2 <- function(argList=NULL){
fit <- do.call("gls", args = argList)
return(fit)
}
# make data ---------------------------------------------------------------
set.seed(1)
n <- 20
x <- sort(rlnorm(n, meanlog = 0.25, sdlog = 1.5))
b <- 100
cv <- 0.5
y <- x*b * rlnorm(n, 0, cv)
dat <- data.frame(x,y)
# fit model ---------------------------------------------------------------
fit <- test.gls(data=dat, model=y~x-1, weights=varExp())
fit2 <- test.gls2(argList=list(data=dat, model=y~x-1, weights=varExp()))
class(fit)
# [1] "gls"
plot(y~x, dat)
lines(dat$x, predict(fit)) # works
# prediction --------------------------------------------------------------
newdat <- data.frame(x=sort(rlnorm(n, meanlog = 0.25, sdlog = 1.5)))
pred <- predict(fit)
newpred <- predict(fit, newdata = newdat)
# Error in eval(expr, envir, enclos) : 'nthcdr' needs a list to CDR down
newpred2 <- predict(fit2, newdata = newdat) # works