Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting the object name for S3 print method failing

Tags:

r

r-s3

Define an object of S3 class "bar" and a print method:

foo=list(1)
class(foo) <- c("bar")
print.bar <- function(x,...){
  cat("print.bar says this was ",deparse(substitute(x)),"\n")
}

Now print(foo) does this:

> print(foo)
print.bar says this was  foo 

Great, but auto-printing fails:

> foo
print.bar says this was  structure(list(1), class = "bar")

I'm guessing this is something to do with the way the line is evaluated as a top-level expression. Had a quick search on R-devel to no avail. Anyone know how to fix it?

The reason I want the name is because the thing I am defining is a function, and I want to be able to put 'try foo(2)' in the print method (getting 'foo' from the name of the object). Yes, you can subclass functions in S3. I suppose there may be other pifalls..

like image 563
Spacedman Avatar asked Feb 10 '11 16:02

Spacedman


2 Answers

This is a rather special case, as R substitutes foo by its value before calling print when you type the name at the command line. This can be illustrated by :

foo=list(1)
class(foo) <- c("bar")
print.bar <- function(x,...){
  print(sys.calls())
}

> foo
[[1]]
print(list(1))

[[2]]
print.bar(list(1))

> print(foo)
[[1]]
print(foo)

[[2]]
print.bar(foo)

ergo, without the name as an attribute (like Aaron showed), there is no way on earth you'll extract the name of the object from anywhere. It's simply not there in the callstack.

like image 190
Joris Meys Avatar answered Oct 03 '22 12:10

Joris Meys


If you're not going to be renaming the object, you could include the name as an attribute and print that instead.

foo <- structure(list(1), class="bar", name="foo")
print.bar <- function(x,...){
  cat("print.bar says this was",attr(x, "name"),"\n")
}

Then it does what you expect:

> print(foo)
print.bar says this was foo 
> foo
print.bar says this was foo 

Unless you use a different name for the same object:

> fooX <- foo
> fooX
print.bar says this was foo 
like image 27
Aaron left Stack Overflow Avatar answered Oct 03 '22 13:10

Aaron left Stack Overflow