hamza ajmal
hamza ajmal

Reputation: 43

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 = ""))
}

Upvotes: 2

Views: 2133

Answers (1)

Esther
Esther

Reputation: 300

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.

Upvotes: 5

Related Questions