Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to print function body with parsed variable

Suppose I have a function which takes some argument k and return another function which 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 can I print the body of five so that it shows rep(5,n) instead of rep(k,n)?

like image 614
qoheleth Avatar asked Dec 14 '17 23:12

qoheleth


1 Answers

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 is telling bquote to evaluate whatever is in the parenthesis, then include the result in the expression.

like image 143
dayne Avatar answered Oct 08 '22 23:10

dayne