Trang Q. Nguyen
Trang Q. Nguyen

Reputation: 139

R: Name an object created within a function with a name defined by the function

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

Upvotes: 0

Views: 205

Answers (1)

baptiste
baptiste

Reputation: 77116

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

Upvotes: 1

Related Questions