I am fitting 100 linear and 100 quadratic models to the same synthetic data with a for loop.
I want to extract (randomly) 5 linear fits, and 5 quadratic fits, and plot these regression functions along with the mean function of the true model.
My thoughts so far:
- pick 10 random numbers
- create a container (data frame?) to hold the 10 models
- enter the for loop, get the fits, if the ith iteration is from the set of random numbers, then hold that model in the container.
- exit for loop, plot all of the fits in the container alongside true model
The main difficulty I'm having is seeing how to create an empty dataframe for class "lm".
Before the for loop, build containers,
fit.container.linear <- list()
fit.container.quadratic <- list()
And pick indices randomly for the models that will go into the container
randy.linear <- sample(1:100,5,replace=F)
randy.quadratic <- sample(1:100,5,replace=F)
And then in the for loop, I get a linear and quadratic model using lm. model.1 is linear. model.2 is quadratic. Now within the for loop I store the models in the containers
for (k in 1:length(randy.linear)){
if (i == randy.linear[k]){
fit.container.linear <- list(fit.container.linear,model.1)
}
}
for (p in 1:length(randy.quadratic)) {
if (i == randy.linear[p]){
fit.container.quadratic <- list(fit.container.quadratic,model.2)
}
}
Exit the for loop.
Now I want to access the containers holding the coefficients, and plot everything on one graph.
results <- list()
. – Ben Bolker