如何提取拟合 nls 模型中使用的参数以用于 do.call 的第二次拟合

How to extract arguments used in a fitted nls model for use in a second fitting with do.call

我正在尝试使用来自拟合 nls 模型的相同原始参数来拟合使用数据子集的第二个模型(用于交叉验证练习)。我可以检索参数(例如 fit$call),但很难将这些参数传递给 do.call

# original model ----------------------------------------------------------
# generate data
set.seed(1)
n <- 100
x <- sort(rlnorm(n, 1, 0.2))
y <- 0.1*x^3 * rlnorm(n, 0, 0.1)
df <- data.frame(x, y)
plot(y~x,df)

# fit model
fit <- nls(y ~ a*x^b, data=df, start=list(a=1,b=2), lower=list(a=0, b=0), algo="port")
summary(fit)
plot(y~x,df)
lines(df$x, predict(fit), col=4)



# perform model fit on subset with same starting arguments ----------------
# df sampled subset
dfsub <- df[sample(nrow(df), nrow(df)*0.5),]
dim(dfsub)
plot(y~x, dfsub)

ARGS <- fit$call # original call information
ARGS$data <- dfsub # substitute dfsub as data
ARGS <- as.list(ARGS) # change class from "call", to "list"

fitsub <- do.call(nls, args = ARGS )
# Error in xj[i] : invalid subscript type 'closure'

此外,作为旁注,fit$data 只是 returns 数据对象的名称。数据是否实际上也包含在拟合的 nls 对象中(正如 lm 和其他模型拟合有时所做的那样)?

使用update添加子集参数:

nr <- nrow(df)
update(fit, subset = sample(nr, nr * 0.5) )

您可以使用 update 函数用不同的数据集重新拟合模型:

fitsub <- update(fit, data = dfsub)