I want to overwrite the plot method for a certain class. I want the expression string to be used as the axis label. However it seems that the method dispatch somehow evaluates the expression so I can't retrieve the original expression the way I expected(sorry if I am using the wrong vocabulary here). In the following a minimal example:
library(rlang)
make_s = function(x) structure(x, class = "s")
plot2= function(x) print(enexpr(x))
plot.s = function(x) print(enexpr(x))
variable_name = make_s(1)
plot2(variable_name)
#Output:
#variable_name
plot(variable_name)
#Output:
#[1] 1
#attr(,"class")
#[1] "s"
My expectation was that plot.s
returns "variable_name" which it doesn't. Why is that and how to remedy this?
That appears to be a bug or misuse of the rlang::enexpr
function. I don't know that function (and its docs are the usual tidyverse mishmash of made up words without any real explanation), so here's the base way to do what you want:
make_s = function(x) structure(x, class = "s")
plot.s = function(x) print(deparse1(substitute(x)))
variable_name = make_s(1)
plot(variable_name)
#> [1] "variable_name"
Created on 2023-12-15 with reprex v2.0.2