简体   繁体   中英

R user-defined save load functions | Passing variable names as arguments using deparse(substitute)

I'm trying to write a function that takes folder name and variable name as arguments passed into R's base save/load functions. I've used deparse(substitute(variable name)) to pass variable name as argument name, based on comments on other posts.

Trial: the folder name is SData in my working directory and the variables are x and y; I want to create an .RData file for each x and y.

x <- 1:100
y <- "string"

getSave <- function(folder, rdata){
    save(rdata, file = paste0("./", deparse(substitute(folder)), "/", 
                              deparse(substitute(rdata)), ".RData"))
}

getSave(SData, x)
getSave(SData, y)

These files are saved as x.RData and y.RData, as I wanted. Now, let's clear the environment and load the data using a similar function:

rm(x, y)

getLoad <- function(folder, rdata){
    load(paste0("./", deparse(substitute(folder)), "/",
                deparse(substitute(rdata)), ".RData"))
}

getLoad(SData, x) # does not work
getLoad(SData, y) # does not work

load("./SData/x.RData") # loads x but with variable name rdata
load("./SData/y.RData") # loads y but with variable name rdata

The getLoad() should've loaded x.RData as x in the environment, the same for y. While the function does not work, the base load function loads both the variables in the environment with the name rdata with respective values of x and y.

I'm trying to understand how deparse(substitute()) is working here. Also, what's causing this loading issue with the substitution of the real variable name with the argument variable name inside my function?

You need to do the changes in both save and load functions. Use list argument in save function to save the data with the same variable names as passed value.

getSave <- function(folder, rdata){
  val <- deparse(substitute(rdata))

  save(list = val, 
       file = paste0("./", deparse(substitute(folder)), "/", val, ".RData"))
}

getSave(SData, x)
getSave(SData, y)

To load the data, specify the environment as global since by default the values are loaded in the called environment. Since you are loading the data in a function by default the values are loaded inside the function only.

getLoad <- function(folder, rdata){
  load(paste0("./", deparse(substitute(folder)), "/", deparse(substitute(rdata)), ".RData"), 
       envir = .GlobalEnv)
}

getLoad(SData, x)
getLoad(SData, y)

So the issue was not related to deparse , substitue but how save and load functions work inside a user defined function.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM