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?