Reputation: 89
I would like to use values within variables for defining functions in R. However, after declaring the function I can still see the variable names instead of their values inside the function definition. Here is an example:
> variable <- 10
> fn <- function() {message(variable*2)}
> fn
function() {message(variable*2)}
And what I am expecting to see:
> variable <- 10
> fn <- function() {message(variable*2)}
> fn
function() {message(10*2)}
How could I fix this?
Upvotes: 0
Views: 88
Reputation: 270045
Rather than modify the function code wrap the variable together with the function in the same environment using local
. (Depending on what is in the function you may need to add the envir = .GlobalEnv
argument to local
.)
fn <- local({
variable <- 10
function() {message(variable*2)}
})
fn()
## 20
Upvotes: 3
Reputation: 44957
Like @MrFlick in his comment, I don't know why you would want to do this. But in case you have a reason for it, here's one way to do it:
fn <- function() 1 # dummy declaration
body(fn) <- substitute(
# The body of the function
{message(variable*2)},
# The substitutions you want
list(variable = 10))
fn
#> function ()
#> {
#> message(10 * 2)
#> }
Created on 2024-09-05 with reprex v2.1.1
Edited to add:
I just read your response to his comment. I think you are taking the wrong approach here. This is a better way to do what you want:
makeFn <- function(variable) {
force(variable) # Make sure it is evaluated
function() {message(variable*2)}
}
fn10 <- makeFn(10)
fn20 <- makeFn(20)
fn10()
#> 20
fn20()
#> 40
Created on 2024-09-05 with reprex v2.1.1
Upvotes: 3