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

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

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.