简体   繁体   中英

How to save multiple objects as .Rdata files with purrr

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 (eg 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?

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")))

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