How to save content from data sets to files dynamically?

Asked

Viewed 22 times

-2

I have an array with the name of my datasets and want to store the contents of them in files .csv individual dynamically.

With the code below, the files are created, but instead of the content of the data sets, the name of the data set is saved. I have already used the assign() and it’s the same.

dsets <- c('wairlines', 'wairports', 'wflights', 'wplanes', 'wweather')

for(ix in 1:length(dsets)) {
  write.csv(dsets[ix], file = paste0('./input_orig/',dsets[ix],'.csv'))
}

The above code should be equivalent to:

write.csv(wairlines,file='./input_orig/wairlines.csv')
write.csv(wairports,file='./input_orig/wairports.csv')
write.csv(wflights,file='./input_orig/wflights.csv')
write.csv(wplanes,file='./input_orig/wplanes.csv')
write.csv(wweather,file='./input_orig/wweather.csv')

From now on my thanks

  • Thanks for the copydesk... learning...

2 answers

2


dsets is a string array, not a date list..
To access the data.frames you have to retrieve them with get.
In addition, it is not necessary to compose file names one by one, the paste is a vector function.

dsets <- c('wairlines', 'wairports', 'wflights', 'wplanes', 'wweather')
fl <- paste0('./input_orig/', dsets, '.csv')
env <- .GlobalEnv
for(ix in seq_along(dsets)) {
  write.csv(get(dsets[ix], envir = env), file = fl[ix])
}

Or, without the array of filenames fl:

env <- .GlobalEnv
lapply(dsets, function(x){
  fl <- paste0('./input_orig/', x, '.csv')
  write.csv(get(x, envir = env), file = fl)
})

0

Guys, I found the solution.... the correct code should be.... dsets <- c('wairlines', 'wairports', 'wflights', 'wplanes', 'wweather')

for(ix in 1:length(dsets)) { write.csv(get(dsets[ix]), file = paste0('. /input_orig/',dsets[ix],'. csv')) } This get() makes all the difference and opens a super-dimension of function automation..

  • Rui... Thanks... I just saw... credit will be given...

Browser other questions tagged

You are not signed in. Login or sign up in order to post.