[R] Correct way to handle class

Marc Girondot m@rc_grt @end|ng |rom y@hoo@|r
Thu Apr 14 12:34:24 CEST 2022

Dear member of the list,

I search for the correct way to handle class.

I learn recently that inherits() was the correct way to test class:

inherits(x, what, which = FALSE)

For this part it is ok.

But now I have questions about the correct procedure to set class.

Previously I used:

result <- "Je suis donc je pense"
class(result) <- "ECFOCF"

But I loose the previous class "character". It is still present in 
mode(result) but sometimes it can be a problem.

For example here:

 > resultL <- data.frame(A=c(1,2), B=c(3, 4))
 > class(resultL)
[1] "data.frame"
 > class(resultL) <- "ECFOCF"
 > resultL
[1] 1 2

[1] 3 4

[1] "ECFOCF"
[1] 1 2

I lost the data.frame structure when I set the new class. It is seen as 
a list by:

 > mode(resultL)
[1] "list"

So I use:

result <- "Je suis donc je pense"
class(result) <- unique(append("ECFOCF", class(result)))

I use append because I don't want loose the original class. I use 
unique() to prevent the same class being put several times in the object.

However, Using this formula, I am not 100% sure the "ECFOCF" is the 
first class. If it is not, it could prevent plot.ECFOCF to take in 
charge the plot of this object.

An alternative could be:

 > result <- "Je suis donc je pense"
 > class(result) <- unique(append("ECFOCF", class(result)[class(result) 
!= "ECFOCF"]))
 > class(result)
[1] "ECFOCF"    "character"

Then I am sure that "ECFOCF" class is the first one.

Is it the correct way to define class or I am in wrong direction?

Thanks a lot


More information about the R-help mailing list