替换R函数中变量名的多个实例并保存修改后的函数

问题描述 投票:0回答:1

背景

考虑以下愚蠢的 MWE:

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

}

我想用

VarA
VarB
VarX
替换
VarY
以获得:

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

然后我想保存

new_fun
以便我可以使用它。

我的方法

我在想类似的事情

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

但是,

new_fun
NULL
,我不确定如何最好地将其保存到文件夹中。

r function
1个回答
2
投票

在身体上使用

substitute

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
## }
© www.soinside.com 2019 - 2024. All rights reserved.