0

I'm trying to loop through a character vector, and for each value, run a slightly different query. I then want to capture the results, and save them locally as an rdata file. Once that's saved, I can delete the R object.

I know that I should be doing this as an apply/sapply and would appreciate a tip for how to do that...

However, my main issue is that while the rdata files save nicely with the names I'd hoped for (i.e. "TABLE1", "TABLE2"), when I load them back into R, they all have the object name of "thisname", with a single value corresponding to the name I'd hoped for (e.g. "TABLE1"). I have been attempting to make this work for far too long .

If anyone has a suggestion, I'd appreciate it!

tables = c('TABLE1','TABLE2')
for (i in 1:length(tables)){
       thisname=paste0(tables[i])
       data= sqlQuery(oracle.channel, paste("select * from",table_renamer(tables[i]),"WHERE ROWNUM<10;"))
       assign(thisname,data)
       save(thisname, file=file.path(paste0( tables[i],".RData")))
        rm(thisname)
        rm(thisdf)
      }
0

2 Answers 2

0

Use saveRDS(thing, file="file.rds").

This only saves the object's value, so you read it in by assignment to any name you like:

foo = readRDS("file.rds")

Or if you already have saved a bunch of things to .RData files, load them into a new environment and get the value, something like:

e = new.env()
load("foo.RData", environment=e)
foo = e$thisname

Wrap that into a function for neatness.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for looking. I couldn't use saveRDS() because my package requires that data be loaded via data(), which limts me to .RData and rda files. In the end I found a solution on <gasp> stack overflow, and marked my question as a duplicate. I will post my final solution below in case anyone finds this post.
0

My final solution did use sapply, which is nice:

 #make a custom function to do the data handling, including saving
 saveit <- function(x, oracle.channel, data.dir){
      assign(x,sqlQuery(oracle.channel, paste("select * from",table_renamer(x),"WHERE ROWNUM<10;")))
      save(list=x, file=file.path(data.dir, paste0( x,".RData")))
}
#sapply to make it happen
sapply(tables, simplify=TRUE, saveit, oracle.channel, data.dir)

The real trick was saving the list: save(list=x, ...), which I learned here

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.