Search code examples
rfunction

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

 return(list("VarA" = VarA, "VarX" = VarX))
}

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

new_fun <- function(x) {
  VarB <- sum(x)
  VarB <- 2 * VarB
  VarY <- VarB %% 2
  
 return(list("VarB" = VarB, "VarY" = VarY))
}

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
    ## }