[R] Modificatio of function body within a function

Grzegorz Smoliński g@@mo||n@k|1 @end|ng |rom gm@||@com
Fri Apr 1 21:50:01 CEST 2022


Hi,

I'm working on a presentation regarding the modification of the
function body on-the-fly and just discovered something I don't
understand. I would like to modify a body of the function within a
function, but I see that it is possible only when explicitly referring
to the environment where the function is defined:

fun1 <- function() {
  1
  body(fun1)[[2]] <- "one"
}
fun1()
body(fun1)
#> {
#>     1
#>     body(fun1)[[2]] <- "one"
#> }

fun2 <- function() {
  2
  env <- environment(fun2)
  body(env$fun2)[[2]] <- "two"
}
fun2()
body(fun2)
#> {
#>     "two"
#>     env <- environment(fun2)
#>     body(env$fun2)[[2]] <- "two"
#> }

Can I get some explanation or some links / articles about this,
please? I thought it won't be a difference and I should be able to
modify a function body also in the first case, because I'm changing
something in the parent environment being in the child environment.

Best regards,

Grzegorz



More information about the R-help mailing list