1

How does one load an .RData file that we know is a data frame such that one can use it as such? So I'm thinking along the lines of:

PATH <- getwd()
FILE_NAME <- "some_data_frame"
FILE_EXTENSION <- ".RData"
FILE_PATH <- paste0(PATH, "/", FILE_NAME, FILE_EXTENSION)

load(FILE_PATH)

So I did some more searching and I have an answer to my own question. This is what worked for me:

load(FILE_PATH)
df <- eval(parse(text = FILE_NAME))

It seems that the generic way to convert a string to an object is to use this eval-parse idiom.

Somnath
  • 27
  • 5
  • Have you tried your idea? What happened? Did it work? If it didn't, did you get an error message? If so, what did it say? if not, in what way did the result not meet your expectations? – Limey Aug 02 '22 at 11:10
  • 2
    The file isn't a data.frame, it contains a data.frame (and possibly additional other stuff). `load` will load it into your global environment with the same name as it had when is was saved. If you want to save single R objects, use `saveRDS` instead of `save`. – Roland Aug 02 '22 at 11:10

1 Answers1

1

By default, load returns a character vector with the names of variables that have been restored into the current environment.

If you don't want to load everything from the .rda (RData) file into the local environment, then I suggest a temporary environment:

e <- new.env(parent = emptyenv())
load(FILE_PATH, envir = e)
data_frame <- e[["name_of_your_frame"]]

In fact, everything that is in the .rda file is now within the e object. (There is no way to load only one of many objects in the .rds file, it's all-or-nothing.)

r2evans
  • 141,215
  • 6
  • 77
  • 149