r - How to create vector of multiple model objects through loop -
i have large data-set multiple target variables. currently, having issues in writing code/loop 1 of part of model i.e
mod <- list(ah=ah,bn=bn). #detailed code 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) (i in names(mod)) { jk[[i]] <- predict(mod[[i]], jk) }
problem if there 200 models cumbersome task write ah=ah, bn=bn 200 times. therefore, need loop run same use in below predict function.
if concerned getting 'mod' in list
, create objects within new environment , values using mget
after listing objects (ls()
) 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 option using paste
mod1 <- mget(paste0(c("a", "b"), c("h", "n")), envir = e1) names(mod1) #[1] "ah" "bn"
this useful if there many objects , want return them in sequence i.e. suppose have 'ah1', 'ah2', ... in 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 loop predict
based on '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
Post a Comment