7

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?

2
  • Your question is a duplicate of this Q&A. 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 might be interseting for you. Commented Nov 28, 2017 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. Commented Nov 28, 2017 at 10:28

1 Answer 1

18

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")))
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.