Reputation: 3796
I am trying to save a series of models using purrr
's walk()
functions, and am getting the following error:
"Error in map2(.x, .y, .f, ...) : object 'model' not found"
library(dplyr)
library(tidyr)
library(purrr)
mt_models <-
mtcars %>%
group_by(cyl) %>%
nest() %>%
mutate(
model = map(.x = data, .f = ~lm(mpg ~ wt, data = .x)),
file_name = paste("model", cyl, "cyl.rda", sep = "_")
)
mt_models %>% walk2(.x = model, .y = file_name, .f = ~save(.x, file = .y))
I can successfully save the models using this code below:
walk2(.x = mt_models$model, .y = mt_models$file_name, .f = ~save(.x, file = .y))
But I am trying to understand why model
is not passing into walk2()
in the first example.
Upvotes: 1
Views: 832
Reputation: 28685
You can use with
to provide an environment in which to search for variables
mt_models %>%
with(walk2(.x = model, .y = file_name, .f = ~save(.x, file = .y)))
Upvotes: 2
Reputation: 887128
Outside the mutate/summarise
and other tidyverse function, we need to do .$
to extract the column
library(dplyr)
library(purrr)
mt_models %>% {
walk2(.x = .$model, .y = .$file_name, .f = ~save(.x, file = .y))
}
Upvotes: 1