2

Situation: I have several data frames that I like to export as CSV files into the working directory for further processing.

Goal: Export a collection of data frames from the workspace as csv files to the working directory by using a single function (batch export).

Details:

My question is not about changing the content of the data frames, so you can just use any example data provided by R for reproduction.

The function I use for exporting a single data frame is

csvExport <- function(data, enc = 'utf8'){
    name <- paste(deparse(substitute(data)), "csv", sep=".")
    con <- file(name, encoding = enc)
    write.csv(data, file = con, row.names=FALSE, quote = TRUE, sep = ";")
    text<-"exported!"
    print(paste(name, text, sep=" "))
}

Since I do not like to call the function for each data frame to export explicitly I am looking for a way to export the data frames by indicating which ones from the workspace I like to export with:

export <- ls()[1:20]

I then tried using this function (with some variation of the for loop) with the above list:

multipleCSVExport <- function(export){
  for (i in export){
    csvExport(i)
  }
}

However, I am not able to create the expected result.

3
  • 2
    You'll probably need to re-write your csvExport function so that the data argument is a character, which is really what you should have done in the first place, most likely. get will be useful. Commented Jan 15, 2014 at 16:18
  • The name will always be i.csv; change that line Commented Jan 15, 2014 at 16:23
  • @ joran: This solved my problem, thanks. Maybe you can turn it into an answer. Commented Jan 15, 2014 at 17:06

2 Answers 2

5

You can use mget to turn your data.frames in the workspace into a list of data.frame and then use lapply or a for loop.

list_df <- mget(ls()[1:20])

lapply(seq_along(list_df),
       function(i) write.table(list_df[[i]], 
                               paste0(names(list_df)[i], ".csv"),
                               row.names = FALSE, quote = TRUE, 
                               sep = ";", dec = "."))
Sign up to request clarification or add additional context in comments.

Comments

1

The qdap package has just such a function: mscv_w. The dev version is what you're after and can be downloaded here (follow directions): https://github.com/trinker/qdap#installation

So something like this works:

mcsv_w(mtcars, CO2, dir="foo")

And if you're more interested in how the function works here is the source code: https://github.com/trinker/qdap/blob/master/R/mcsv_r.R

Comments

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.