ROY ROY - 2 months ago 13
R Question

How to create vector of multiple model objects through loop

I have a large data-set with multiple target variables. Currently, I am having issues in writing code/loop for one of the part of the model i.e

mod <- list(ah=ah,bn=bn).

#Detailed code is as follows:

jk<- data.frame(y=runif(40), l=runif(40), m=runif(40), p=runif(40))
ah <- lm(l ~ p, jk)
bn <- lm(m ~ y, jk)
mod <- list(ah=ah,bn=bn)
for (i in names(mod))
{
jk[[i]] <- predict(mod[[i]], jk)
}


Problem is that if there are 200 models then it will be cumbersome task to write ah=ah, bn=bn for 200 times. Therefore, I need a loop to run the same so as to use in below predict function.

Answer

If we are only concerned about getting the 'mod' in a list, create the objects within a new environment and get the values using mget after listing the objects (ls()) from the environment

e1 <- new.env()
e1$ah <- lm(l ~ p, jk) 
e1$bn <- lm(m ~ y, jk) 
mod <- mget(ls(envir=e1), envir = e1)
mod
#$ah

#Call:
#lm(formula = l ~ p, data = jk)

#Coefficients:
#(Intercept)            p  
#     0.4800       0.0145  


#$bn

#Call:
#lm(formula = m ~ y, data = jk)

#Coefficients:
#(Intercept)            y  
#    0.37895     -0.02564  

Or another option is using paste

mod1 <- mget(paste0(c("a", "b"), c("h", "n")), envir = e1)
names(mod1)
#[1] "ah" "bn"

This will be useful if there are many objects and we want to return them in a sequence i.e. suppose we have 'ah1', 'ah2', ... in an environment

e2 <- new.env()
e2$ah1 <- 1:5
e2$ah2 <- 1:6
e2$ah3 <- 3:5
new1 <- mget(paste0("ah", 1:3), envir = e2)
new1
#$ah1
#[1] 1 2 3 4 5

#$ah2
#[1] 1 2 3 4 5 6

#$ah3
#[1] 3 4 5

Now, applying the loop to get the predict based on the 'mod'

for (i in names(mod)){ 
 jk[[i]] <- predict(mod[[i]], jk)
}
head(jk)
#         y          l         m         p        ah        bn
#1 0.2925740 0.47038243 0.5268515 0.9267596 0.4934493 0.3714515
#2 0.2248911 0.37568719 0.1203445 0.5141895 0.4874671 0.3731871
#3 0.7042230 0.27253736 0.5068240 0.6584371 0.4895587 0.3608958
#4 0.5188971 0.21981567 0.2168941 0.7158389 0.4903910 0.3656480
#5 0.6626196 0.04366575 0.3655512 0.3298476 0.4847942 0.3619626
#6 0.9204438 0.07509480 0.3494581 0.7410798 0.4907570 0.3553514

data

set.seed(24)
jk<- data.frame(y=runif(40), l=runif(40), m=runif(40), p=runif(40))
Comments