Home > OS >  How to save multiple objects as .Rdata files with purrr
How to save multiple objects as .Rdata files with purrr

Time:06-02

I have a list of objects in my R envir and I would like to save them as correspondent .Rdata files. I know how to save them individually, but I would like to do it iteratively with purrr (e.g. using map or walk?). I tried several times and I always get an error.

# Example dfs 
my_mtcars <- mtcars
my_orange <- Orange
list_dfs  <-  list (my_mtcars = my_mtcars, my_orange = my_orange)

# Individually I would do: 
saveRDS(object = my_mtcars, file = paste0("my_mtcars", ".RDS"))

# Here is one of my [WRONG] attempts
n <- 1:2 
purrr::walk2(.x = list_dfs, .y =n,  ~saveRDS(.x, file = paste0(names(list_dfs[n]), ".RDS")))

Any ideas?

CodePudding user response:

I think better option would be to use imap/iwalk here which passes the data (.x) as well as name (.y) to the function.

purrr::imap(list_dfs, ~saveRDS(.x, file = paste0(.y, ".RDS")))

With iwalk -

purrr::iwalk(list_dfs, ~saveRDS(.x, file = paste0(.y, ".RDS")))
  • Related