Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

In R, grab & return loaded dataframe variable with dynamic name

We have a directory with files data1.rda, data2.rda, data3.rda and the following function in R to load and return the data. load(data1.rda) returns a dataframe named data1, with the same naming pattern for other .rda files loaded:

returnData <- function(id) { 
  load(paste0("data", id, ".rda"))
  return(paste0("data", id))
}

data1 <- returnData(1)

Obviously the above doesn’t work because the string data1 is returned rather than the dataframe. How can we return the named dataframe data1 in the example above?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

A possible solution:

returnData <- function(id) { 
  load(paste0("data", id, ".rda"))
  return(eval(parse(text = paste0("data", id))))
}

data1 <- returnData(1)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading