How to print function body with collapsible variable

Suppose I have a function that takes some argument k and returns another function that takes argument n but uses k in its function body.

 makeFn <- function(k) { function(n){ rep(k,n) } } five <- makeFn(5) five(3) # [1] 5 5 5 body(five) # { # rep(k, n) # } 

How to print the body of five so that it shows rep(5,n) instead of rep(k,n) ?

+5
source share
1 answer

One option is to combine eval and bquote .

 makeFn <- function(k) { eval(bquote(function(n) rep(.(k),n))) } five <- makeFn(5) body(five) # rep(5, n) 

The notation .() Tells bquote to evaluate everything in the parenthesis and then include the result in the expression.

0
source

Source: https://habr.com/ru/post/1274083/


All Articles