我有一个功能f <- function(x){x}
。我想插入该行,x <- 2*x
使其f
最终成为
function(x){
x <- 2*x
x
}
Run Code Online (Sandbox Code Playgroud)
我知道我应该使用body()
,但到目前为止我只知道如何更换整个身体,这对于我的真正目的来说并不实用。
这是另一种方法(用于magrittr
简化事情)
f <- function(x){x}
f(2)
# [1] 2
# library(magrittr)
body(f) <- body(f) %>% as.list %>% append(quote(x<-2*x), 1) %>% as.call
f(2)
# [1] 4
Run Code Online (Sandbox Code Playgroud)
或者甚至简单地
body(f) %<>% as.list %>% append(quote(x<-2*x), 1) %>% as.call %>% as.expression
Run Code Online (Sandbox Code Playgroud)
但我觉得我可能缺少一种更简单的方法
您可以编写一个更传统的函数,magrittr
而无需......
funins <- function(f, expr = expression(x<-2*x), after=1) {
body(f)<-as.call(append(as.list(body(f)), expr, after=after))
f
}
Run Code Online (Sandbox Code Playgroud)
您可以使用它来插入任何表达式
f <- function(x){x}
g <- funins(f, expression(print("hi"), x<-3*x))
f(2)
# [1] 2
g(2)
# [1] "hi"
# [1] 6
Run Code Online (Sandbox Code Playgroud)