0

I am having a hard time trying to create residual plots for multiple models in a loop. I used a loop to create the models:

nameIndex=1
name=character(length=nrow(resp))


for(i in resp$resp){

  y=response.data[,i]
  df=data.frame(y, modelpredictors) #this creates a temporary data frame for you 
  nam=paste("MODEL", nameIndex, sep=".") #Create unique model names to use later
  model=lm(y~.,data=df)

  assign(nam, model)
  name[nameIndex]=nam #saving model names in a vector to use later
  nameIndex=nameIndex+1
}

Now, I want to do a loop to make residual plots.

par(mfrow=c(2,3))
for(i in nrow(resp)){
  plot(fitted(cat("MODEL.",i)),residuals (cat("MODEL.",i)))
}

However, I am getting the error

Error in plot.window(...) : need finite 'xlim' values

I want to know how to call the models that I created in the first loop in a orderly fashion to use in plotting loops and other analysis that I want to do to all of the models.

Chloee Robertson
  • 195
  • 2
  • 12

1 Answers1

1

The cat() function write to the terminal (or disk), it does not generate variable names. The function that corresponds to assign() is get(). You should be able to do

par(mfrow=c(2,3))
for(i in nrow(resp)){
  plot(fitted(get(paste0("MODEL.",i))),residuals(get(paste0(("MODEL.",i))))
}

although building variable names with strings like that is not generally a good strategy. You probably should be storying things in a list. If you actually included a reproducible example it would be easier to make better recommendations for a more "R-like" solution. Maybe something like

models <- lapply(resp$resp, function(r) {
  y <- response.data[,r]
  lm(y~., data=data.frame(y, modelpredictors))
})

then

par(mfrow=c(2,3))
lapply(models, function(m) {
  plot(fitted(m), residuals(m))
})
Community
  • 1
  • 1
MrFlick
  • 195,160
  • 17
  • 277
  • 295