How can one capture the object name of an argument to a generic function call?
A toy example will clarify the question and, as I understand it, core issue. Consider an object of some S3 class:
X <- structure("blah", class = "SomeClass")
For SomeClass
objects, I want to make a (silly) print
method that simply prints the name of the object. In particular, when I enter X
at the console, I want to see the name X
:
> X
X
I tried to implement this with the following method:
print.SomeClass <- function(y) cat(deparse(substitute(y)))
Invoking print(X)
gives X
, as expected. But just entering X
(uppercase) at the console gives x
(lowercase):
> print(X)
X
> X
x
What gives? I surmise this x
is derived from the name of the argument of the generic function print
. How must I modify print.SomeClass
so that directly invoking X
gives X
?
The issue seems to be a discrepancy between displaying an object via bare invocation at the console and displaying an object via print
—they are not exactly equivalent. I suspect, I may need to supply substitute()
with a specific environment elsewhere on the call stack. But in that case, I don't know which one would bridge the discrepancy.