Quantcast
Channel: Active questions tagged r - Stack Overflow
Viewing all articles
Browse latest Browse all 201839

referring to lists within larger lists from a loop

$
0
0

I want to cycle through many models and output the coefficients

Basically I want to do what the code below does. But then refer to each object in the list that is generated that contains the object list from each model and the data objects generated by the model statement.

So an example of the coefficients I want is below

library(broom)
library(tidyr)
library(dplyr)
library(nnet)
db<-mtcars
modelmpg<-multinom(cyl ~ vs + carb+ mpg, data = db)

modelmpg <- tidy(modelmpg, exponentiate = T)
modelmpg1 <- modelmpg[-5]
modelmpg2 <- reshape2::melt(modelmpg1, id=(c("y.level", "term")))

modelmpg3 <- spread(modelmpg2, y.level, value )
modelmpg3$term[modelmpg3$variable %in% c("std.error", "p.value")] <- ""

now say I wanted to do this for a whole mess of variables and run the model for each combination of vs, carb and a third variable i which is one of the variables identified in an identified varlist

#create varlist
varlist.iv <- c("mpg", "disp", "drat", "wt")

#create a list of the results for each multinomial log regression 
models <- lapply(varlist.iv , function(x) {multinom(substitute(cyl ~ vs + carb + i ,list(i = as.name(x))), data = db)})

here is where everything falls apart. I try to refer to the coefficients within the model as [[i]] in a list in models. and it does not recognise it. I've also tried [[i]][[3]] which i believe means third item in the ith object in the list named models? See below (the code does not work but it shows what I am trying to do)


#Run a loop for each of the data manipulation steps

for (i in models){
  mod <- tidy(mod1[[i]], exponentiate = T)
  mod[,paste0(i,"1")] <- mod
  aa = paste0(i,"1")
  mod[,paste0(aa,"2")] <- aa[-5]

basically trying to replicate the first block of code but in a loop for all i variables in varlist.iv

Can anyone help me out? Some help with the loop would be excellent but helping me understand how to identify which object is in which list would really help me. I have read the help documentation but I must be misunderstanding it.


Viewing all articles
Browse latest Browse all 201839

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>