[R] Strange behavior with S3 class

Philippe Massicotte pmassicotte at hotmail.com
Fri Jan 22 11:36:46 CET 2016


> That says the internal variable name is preserved but while it still has the 'eem' class the name is reported differently.
> That is presumably because you defined a 'names' function for objects of class 'eem' which returns the contents of $sample as the name, not "sample". Looks like str is using your names.eem method to extract the name of each component of your object, which is kind of what redefining 'names' asks for. And just to demonstrate that str does indeed use the current class's names method:
>
> names.eem <- function(x, ...){  "AnotherName"}
> str(test1)
> # List of 1
> #  $ AnotherName: chr "justaname"
> #  - attr(*, "class")= chr "eem"
>
> So it isn't your '<-', it's because you overrode 'names'

You are absolutely right I made a mistake describing the problem.

So my question is how I can implement the "names" method for my class 
without having this problem. The following piece of code reproduce the 
problem I am facing.

names.eem <- function(x, ...){
   x$sample
}

# First constructor
eem1 <- function(sample){
   eem <- list(sample = sample)
   class(eem) <- "eem"
   return(eem)
}

# Second constructor
eem2 <- function(sample){
   eem <- list(sample = sample)
   class(eem) <- "eem2"
   return(eem)
}

test1 <- eem1("justaname")
test2 <- eem2("justaname")

str(test1)
str(test2)

Thank you for your help,
Philippe



More information about the R-help mailing list