0

I need to simulate some data, and I would like to have a function with everything built in, so I just need to run

simulate(scenario="xxx")

This function stores all the simulated datasets for the designated scenario in a list called simdat. Within the function, I want to rename that list "simdat.xxx" and save it out as "simdat_xxx.RData", so later on I can just load this file and have access to the list simdat.xxx. I need the list to have a name that refers specifically to which batch it is, because I am dealing with a lot of batches and I may want to load several at the same time.

Is there a way to, within a function, make a name and use it to name an object? I searched over and over again and could not find a way to do this. In desperation, I am resorting to doing this: within the function,

(a) write a temporary script using paste, which looks like this

temp.fn <- function(simdat){
  simdat.xxx <- simdat
  save(simdat.xxx,file="simdat_xxx.RData")
  }

(b) use writeLines to write it out to a .R file

(c) source the file

(d) run it

This seriously seems like overkill to me. Is there a better way to do this?

Thanks much for your help!

Trang

  • you may want to consider the pair `saveRDS()/readRDS()`; you simply assign the object to whatever name you fancy when you read it back in (e.g. based on the Rdata filename). – baptiste Sep 27 '14 at 00:56
  • @baptiste - Wow! Thanks for this, too. Really appreciate it! – Trang Q. Nguyen Sep 27 '14 at 01:02
  • I am going for `saveRDS()`. It's so much cleaner. I wonder why didn't I think of searching for another save option before. I guess the hardest thing to know is what you don't know. – Trang Q. Nguyen Sep 27 '14 at 01:22

1 Answers1

1

Try this,

simulate <- function(scenario="xxx"){

   simdat <- replicate(4, rnorm(10), simplify=FALSE)
   data_name <- paste("simdat", scenario, sep=".")
   assign(data_name, simdat)
   save(list = data_name, file = paste0("simdat_", scenario, ".Rdata"))
}
baptiste
  • 75,767
  • 19
  • 198
  • 294
  • Thank you so much for this. `assign` is better than any headache pill! Thanks also for `paste0`. I always used `paste(sep="",...)` before and this is so much more neat. – Trang Q. Nguyen Sep 27 '14 at 00:58