Home > Mobile >  Evaluate and save Argument variable value during function definition?
Evaluate and save Argument variable value during function definition?

Time:04-29

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

CodePudding user response:

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

CodePudding user response:

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)
## 2
  •  Tags:  
  • r
  • Related