r-如何提取拟合nls模型中使用的参数,以便在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只是返回数据对象的名称。数据是否也包含在拟合的nls对象中(就像lm和其他模型拟合有时所做的那样)?

使用update添加子集参数:

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

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

fitsub <- update(fit, data = dfsub)

最新更新