Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Replace multiple Instances of a variable name in an R function and save the modified function

Context

Consider the following silly MWE:

old_fun <- function(x) {
  VarA <- sum(x)
  VarA <- 2 * VarA
  VarX <- VarA %% 2

}

I want to replace VarA with VarB and VarX VarY to get:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

new_fun <- function(x) {
  VarB <- sum(x)
  VarB <- 2 * VarB
  VarY <- VarB %% 2
}

Then I want to save new_fun so I can use it.

My Approach

I was thinking something like

# Variables to replace
variables_to_replace <- c("VarA", "VarX")
new_variables <- c("VarB", "VarY")

# Replace variables in the function code
modified_code <- deparse(substitute(old_fun))
for (i in seq_along(variables_to_replace)) {
  modified_code <- gsub(variables_to_replace[i], new_variables[i], modified_code)
}

# Create a new function with replaced variables
new_fun <- eval(parse(text = modified_code))

However, new_fun is NULL and I’m unsure how best to go about saving it to a folder.

>Solution :

Use substitute on the body:

new_fun <- old_fun
body(new_fun) <- do.call("substitute", 
  list(body(old_fun), list(VarA = as.name("VarB"), VarX = as.name("VarY"))))
dump("new_fun", "new_fun.R") # write it out


new_fun
## function (x) 
## {
##     VarB <- sum(x)
##     VarB <- 2 * VarB
##     VarY <- VarB%%2
## }
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading