Getting The Name of a Dataframe from Loading a .Rda File in R

getting the name of a dataframe from loading a .rda file in R

I had to reinstall R...somehow it was corrupt. The simple command which I expected of

load("al.rda")

finally worked.

Getting the name of the data set in an '.rda' file

If you have the name of an object, but you want the actual value, then use the get function. So you can do something like:

combineddata <- rbind( get(nameofthedataframe), mydata2 )

Saving data frames as .Rda files and loading them using loops

Here's a minimal reproducible example showing how to write data.frames as RDS files in a loop, and then read them back into the R environment in a loop:

# Make 3 dataframes as an example
iris1 <- iris2 <- iris3 <- iris

df_names <- c("iris1", "iris2", "iris3")

# Saving them
for (i in 1:length(df_names)) {
saveRDS(get(df_names[i]), paste0(df_names[i], ".RDS"))
}

# Confirm they were written
dir()
# [1] "iris1.RDS" "iris2.RDS" "iris3.RDS"

# Remove them
rm(iris1, iris2, iris3)

# Load them
for (i in 1:length(df_names)) {
assign(df_names[i], readRDS(paste0(df_names[i], ".RDS")))
}

Load a .rda file and iterate over its objects

Two thoughts:

  1. Load explicitly into a new empty environment, then work on them there:

    e <- new.env(parent = emptyenv())
    load(filename, envir = e)
    out <- eapply(e, function(x) {
    # do something with x
    })
  2. From ?load, it returns a "character vector of the names of objects created, invisibly". If you capture the (invisible) vector, you should be able to do something like:

    nms <- load(data)
    for (nm in nms) {
    x <- get(nm)
    # do something with x
    # optional, save it back with assign(nm, x)
    }
    # or to capture all data into a list (similar to bullet 1 above)
    out <- lapply(lapply(nms, get), function(x) {
    # do something with x
    })

I prefer the first (environment-based) solution for a few reasons:

  • it will never overwrite anything in .GlobalEnv ... having learned that the hard way some times with unreproducible issues, this is huge for me
  • it encourages a list-like way of doing things, more important when most or all of the objects in the .rda file are the same "thing" (e.g., frame, list) and I plan on doing the same actions to each of them
  • if there is ever any doubt as to the source of the data, it won't clutter any of my namespace or global environment


Related Topics



Leave a reply



Submit