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

Time:06-24

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?

CodePudding user response:

A possible solution:

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

data1 <- returnData(1)
  •  Tags:  
  • r
  • Related