1

I have a named list of data frames and want to write each data frame out to a CSV, using the data frame name as the filename. How can I modify my function to do that? The function below gives me the entire data frame in the file name instead of the name of the data frame.

a <- data.frame('col1' = c(1,2,3))
b <- data.frame('col1' = c(3,4,5))
mylist <- list(a,b)
names(mylist) <- c('a', 'b')
lapply(mylist, function(x) write.csv(x, file = paste0(x, '.csv')))

1 Answer 1

4

With base R you can do.

lapply(names(mylist), function(x) {write.csv(mylist[[x]], file = paste0(x, ".csv"))})

Or you can use the shortcut command iwalk from the tidyverse library purrr.

iwalk(mylist, function(x, y) {write.csv(x, file = paste0(y, ".csv"))})

## Or this alternative syntax.

iwalk(mylist, ~write.csv(.x, file = paste0(.y, ".csv")))
Sign up to request clarification or add additional context in comments.

1 Comment

great answer - so many red herrings elsewhere using over complex code.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.