6

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?

Sebastian Sauer
  • 1,555
  • 15
  • 24
  • Your question is a duplicate of [this Q&A](https://stackoverflow.com/questions/35898812/r-read-and-write-multiple-csv-in-a-loop). Since the answer was not accepted I cannot mark your Q as duplicate. Please check the answer that hopefully provides an answer to you, and upvote it afterwards so I mark your question. In case it does not work, I can still support you. Also [this Q&A](https://stackoverflow.com/questions/33054315/write-multiple-csv-files-in-a-loop) might be interseting for you. – Manuel Bickel Nov 28 '17 at 10:01
  • Thanks for the support. This partially works: `lapply(seq_along(dfs), function(i) paste0("data-raw/", i, ".csv"))` - but I need files such as `mtcars.csv`, rather than `1.csv` which is given back by this call. – Sebastian Sauer Nov 28 '17 at 10:28

1 Answers1

15

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")))
Rich Pauloo
  • 7,734
  • 4
  • 37
  • 69
myincas
  • 1,500
  • 10
  • 15