Write Data Frames in Environment into Separate Csv Files

I am trying to export all data sets in R environment into separate csv files using the code below.

For some reason, the exported datasets are empty.

files <- ls()
pattern <- ".csv"

for (i in 1:length(files)) {
  write.csv(files[i], paste(files[i], pattern, sep = ""))
}
1

1 Answer

The problem here is that ls() returns the names of the objects in the environment, not the objects themselves. This means that your loop is trying to export single character strings as a csv files.

To solve this you need to use mget() as follows:

files <- mget(ls())

for (i in 1:length(files)){
  write.csv(files[[i]], paste(names(files[i]), ".csv", sep = ""))
}

Note: you need to be careful that you use [[i]] and [i] the correct way round.

Your Answer

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

Robert Thorne

Robert Thorne

Automotive & Future Transportation Editor

Robert Thorne covers electric vehicle innovations, autonomous driving systems, global mobility trends, and automotive engineering developments.

Share this article
Twitter Facebook Pinterest