'Evaluate and save Argument variable value during function definition?
Consider this function plus_x
:
y <- 1
plus_x <- function(input, x = y){
return(input + x)
}
here the y
default-value for x
is evaluated during the function call.
If I change y
later on, I am also changing the functions behaviour.
y <- 1
plus_x <- function(input, x = y){
return(input + x)
}
y <-10
plus_x(1)
# > 11
Is there a way to "cement" the value for y
to the state it was during the function definition?
Target:
y <- 1
plus_x <- function(input, x = y){
# y is now always 1
return(input + x)
}
y <-10
plus_x(1)
# > 2
Solution 1:[1]
You could define the function using as.function
so that the default value is evaluated at the time of function construction.
y <- 1
plus_x <- as.function(list(input = NULL, x = y, quote({
return(input + x)
})))
plus_x(1)
#> [1] 2
y <-10
plus_x(1)
#> [1] 2
Solution 2:[2]
1) local Surround the function with a local
that saves y
locally:
y <- 1
plus_x <- local({
y <- y
function(input, x = y) input + x
})
y <-10
plus_x(1)
## [1] 2
2) generator Another approach is to create a generator function. This has the advantage that multiple different functions with different y values could be easily defined. Look at demo("scoping", package = "base")
for more examples of using scoping.
gen <- function(y) {
force(y)
function(input, x = y) input + x
}
y <- 1
plus_1 <- gen(y)
y <-10
plus_1(1)
## [1] 2
y <- 2
plus_2 <- gen(y)
y <- 10
plus_2(1)
## [1] 3
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Allan Cameron |
Solution 2 |