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
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
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.