How to call an object with the character variable of the same name

I think you want get.

data <- get(i)

That said, once you start using get (and its counterpart, assign), you usually end up with horrible unreadable code.

For batch analyses like yours, it is often better to read all your data into a list of data frames, then make liberal use of lapply. Something like:

data_files <- list.files()
all_vars <- lapply(data_files, function(file)
{
  vars_loaded <- load(file)
  mget(vars_loaded, parent.frame())
})

mget is the version of get that retrieves multiple variables at once. Here it is used to retrieve all the things that were loaded by the call to load.

Now you have a list of lists: the top level list is related to the file, lower level lists contain the variables loaded from that file.

Leave a Comment