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)
?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With