I am trying to use the same original arguments from a fitted nls
model in the fitting of a second model using a subset of the data (for a cross validation exercise). I can retrieve the arguments (e.g. fit$call
), but am having a hard time passing these arguments to 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'
Also, as a side note, fit$data
just returns the name of the data object. Is the data actually contained within the fitted nls
object as well (as lm
and other model fits sometimes do)?
Use update
to add a subset argument:
nr <- nrow(df)
update(fit, subset = sample(nr, nr * 0.5) )