r-lib / R6

Encapsulated object-oriented programming for R
https://R6.r-lib.org
Other
410 stars 56 forks source link

deparse in active binding function #142

Closed fkgruber closed 6 years ago

fkgruber commented 6 years ago

Hi I wanted to get the construct deparse(substitute(value)) to get the name of the input variable. It works with public functions but not in an active binding. Is there any way to get the name of the variable that is being giving as input to an active binding.

Numbers <- R6Class("Numbers",
  public = list(
      x = 100,
      myfun = function(value){
          return(deparse(substitute(value)))
      }
  ),
  active = list(
      x2 = function(value) {
          print(deparse(substitute(value)))
    }
  )
)

If I do
n <- Numbers$new()
x = 20
n$myfun(x)
n$x2 <- x

I get:

> n$myfun(x)
[1] "x"
> n$x2 <- x
[1] "quote(20)"
wch commented 6 years ago

Sorry, I don't think it's possible because it's a limitation in R itself.

Here's an example with an active binding, without R6 (R6's active bindings are made with the makeActiveBinding function):

makeActiveBinding("x",
  function(value) {
    print(deparse(substitute(value)))
  },  environment()
)

x <- 20
#> [1] "quote(20)"