Solved – Running multiple for loops for multinomial regression in R

I'm using the ANES dataset, which is a repeated cross-sectional study of public opinion and knowledge. I am trying to predict knowledge by individual level characteristics. The data is organized by year, and each respondent is grouped by age into an age cohort.

Essentially, I am trying to run multiple multinomial regression models (the knowledge question has 3 levels: correct, incorrect, and don't know), but I want predictions specific to year the questions were asked and the cohort the respondent belongs to.

Basically, for each year and each cohort = multinom(knowledge ~ gender + education +...)

I have 8 years and 8 cohorts. I tried to do a for loop within a for loop, but for whatever reason it is not working. I tried:

for(i in 1:length(year)){    for(j in 1:length(cohort)){       model <- multinom(knowledge ~ gender + education + income)   } } 

Can someone help me figure out what I'm doing wrong, please? Right now, all this does is give me coefficients for the same year and cohort 100 times…

There are several problems in the code. First, you never refer to the loop variables i and j. You just run the same model multiple times. Second, you have to store the objects returned by the multinom function. Currently, the result is overwritten in each run. You can store multiple objects in a list.

The following code is based on the assumption that your data frame is named dat:

fitlist <- list() # create a list for(i in unique(dat$year)){       for(j in unique(dat$cohort)){         fitlist <- append(fitlist, multinom(knowledge ~ gender + education + income,                                              data = dat[dat$year == i & dat$cohort == j, ]))   } } 

Here, data = dat[dat$year == i & dat$cohort == j, ] creates a subset of the data frame including year i and cohort j. The command append adds an object to the list.

Edit:

The following code includes error handling:

fitlist <- list() for(i in unique(dat$year)){        for(j in unique(dat$cohort)){         tmp <- try(append(fitlist, multinom(knowledge ~ gender + education + income,                                              data = dat[dat$year == i & dat$cohort == j, ])))         if (class(tmp) != "try-error") fitlist <- append(fitlist, tmp)   } } 

Similar Posts:

Rate this post

Leave a Comment