Search code examples
rloopsmodelsummary

object not found when export model summary table in R


I'm trying to export the model summary data into excel in a loop. I need to export 2 variables' coefficients (variables gain & loss) and I have successfully written the coefficients of the intercept and variable 1, but R tells me the object of the third variable is not found.

My codes: run the model by participant number PID, PIDs is the list of PID.

for (i in 1: length(PIDs)) {
   subject<-df[df$PID == PIDs[i],]
   myModel <- glm(gamble~Gain + Loss, data = subject, family=binomial)
   summ <- summary(myModel)

   #save results
   ID[i] <- subject$PID
   intercept_coef[i]<-summ$coefficients[1,1]
   gain_coef[i]<-summ$coefficients[2,1]
   loss_coef[i]<-summ$coefficients[3,1]

}

The coefficients summary table looks like below, I notice that the table is off, as the headers are not corresponding to each column. May be that's the issue?

 Estimate   Std. Error     z value  Pr(>|z|)
 (Intercept) 13.4214135 3353.1375049 0.004002643 0.9968064
 Gain         0.2929938    0.1635471 1.791494960 0.0732139
 Loss         8.3144005 1619.8731372 0.005132748 0.9959047

Error:

occurrednumber of items to replace is not a multiple of replacement length 

Error in loss_coef[i] <- summ$coefficients[3, 1] : 
 object 'loss_coef' not found

What is the issue here? I can get Intercept and Gain all fine.

Thanks!


Solution

  • The variables are required to initialized before we store values in the loop.

    To initialized:

    ID <- 0
    intercept_coef <- 0
    gain_coef <- 0
    loss_coef <- 0
    
    #loop