在this SO question的基础上,我想编写一个通过(1)设置每行可见的()
和(2)将withAutoprint({})
环绕在函数主体周围来操纵其他函数的函数。首先,尽管我对trace()
的某些调用会产生我想要的结果,但是以某种方式我无法弄清楚。
这是一个简单的示例:
# Input function foo
foo <- function(x)
{
line1 <- x
line2 <- 0
line3 <- line1 + line2
return(line3)
}
# some function which alters foo (here called make_visible() )
foo2 <- make_visible(foo)
# so that foo2 looks like this after being altered
foo2 <- function(x)
{
withAutoprint({
(line1 <- x)
(line2 <- 0)
(line3 <- line1 + line2)
(return(line3))
})
}
# example of calling foo2 and desired output/result
> foo2(2)
> (line1 <- x)
[1] 2
> (line2 <- 0)
[1] 0
> (line3 <- line1 + line2)
[1] 2
> (return(line3))
[1] 2
我自己想出了一种使用以下功能的方式:
reveal <- function(.f) {
if (typeof(.f) %in% c("special", "builtin")) {
stop("reveal cannot be applied to primitive functions")
}
fct_formals <- formals(.f)
fct_body <- body(.f)[-1]
.f1 <- function(x) {
(x)
}
.f1_body <- body(.f1)[-1]
.f2 <- function() {}
for (i in seq_along(1:length(fct_body))) {
.f1_body[[1]][[2]]<- fct_body[[i]]
body(.f2)[[1+i]] <- .f1_body[[1]]
}
.f2_body <- body(.f2)[-1]
.f3 <- function() {
withAutoprint({
x
})
}
for (j in seq_along(1:length(.f2_body))) {
body(.f3)[[2]][[2]][[1+j]] <- .f2_body[[j]]
}
formals(.f3) <- fct_formals
.f3
}
将产生以下结果:
foo2 <- reveal(foo)
foo2(1)
> (line1 <- x)
> [1] 1
> (line2 <- 0)
> [1] 0
> (line3 <- line1 + line2)
> [1] 1
> (return(line3))
> [1] 1