Reputation: 327
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(.)))
}
Upvotes: 1
Views: 168
Reputation: 887881
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(.)))
}
Upvotes: 2