Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Write multiple data frames to csv-file using purrr::map [duplicate]

Tags:

r

csv

purrr

PROBLEM:

I have a list of dataframes which should be written to disk as csv-files.

Assume this is the list of data frames:

dfs <- list(iris,
            mtcars)

WHAT DID NOT WORK:

I have tried to build the correct file names like this, but it did not work:

dfs %>% 
  map(~paste0("data-raw/", ., ".csv"))

I hoped that this bit would correctly give back the file names as strings. Instead, map matched each column and each value to the paste0 call.

I also tried the deparse(substitute(.)) trick, but the . was not reckognized correctly in the map call.

The next step would be to write the data frames (elements of dfs) as csv-files.

QUESTION:

How can I use purrr::map(or a similar appraoch) to write each data frame (each element of dfs) as csv-file to disk using write_csv?

like image 317
Sebastian Sauer Avatar asked Nov 28 '17 09:11

Sebastian Sauer


1 Answers

map() and walk() both work, but walk() doesn't print anything, whereas map() will.

Invisible output

list(iris = iris, mtcars = mtcars) %>%
  names(.) %>%
  walk(~ write_csv(dfs[[.]], paste0("data-raw/", ., ".csv")))

Prints output to console

list(iris = iris, mtcars = mtcars) %>%
  names(.) %>%
  map(~ write_csv(dfs[[.]], paste0("data-raw/", ., ".csv")))
like image 176
myincas Avatar answered Nov 08 '22 16:11

myincas