简体   繁体   中英

How to loop over a lm function argument within a purrr:map function in R

I am trying to loop over a lm function embedded within a purrr:map function in R. A map within a map function replacing the forloop would also be a welcome solution but currently I am stuck with a recurring error at the lm.fit step.

Here is a generated code example:


df <-tibble(var1 = rnorm(100,0,1),
            var2 = rnorm(100,0,1),
            var3 = rnorm(100,0,1),
            var4 = rnorm(100,0,1),
            var5 = rnorm(100,0,1),
            var6 = rnorm(100,0,1))



var_list<-df %>% 
  select(var1,var2,var3) %>% colnames()

empty_list <- list()

for (i in var_list){
  
empty_list[[(match(i,var_list))]] <-df %>% 
  nest(-var5,-var6) %>% 
  mutate(fit = map(data, ~ lm(noquote(i) ~ var4, data = .))) %>% 
  mutate(augment = map(fit, ~ broom::augment(.))) 

}

We could create the formula with paste and it is better to initialize the empty list of a particular length as we know the length is based on the length(var_list)

empty_list <- vector('list', length(var_list))
names(empty_list) <- var_list



for (i in var_list){
  
 empty_list[[i]] <- df %>% 
     nest(-var5,-var6) %>% 
     mutate(fit = map(data, ~ lm(paste0(i, '~ var4'), data = .))) %>% 
     mutate(augment = map(fit, ~ broom::augment(.))) 
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM