A brief look at the class mechanism in R

by Karl-Kuno Kunze

This post shows some of the peculiarities of R. The brute force way to assign classes to less structured objecs

  • is not the only way
  • may not be appropriate.

Mechanism 1

Usually, being member of a certain class is expressed by an attribute called ‘class’. So the following three expressions are somewhat equivalent:

You may check with the attributes() and identical() statements, that they are really identical:

Taking the class away, either through a casting function, through unclass(), or through setting the attribute to NULL, is shown here:

All three elements are plain vectors now with one element.

Mechanism 2

However, look at this:

What is going on here? Although we took away the class, it still remembers its class ‘matrix’.

Let’s have a closer look at the attributes:

In fact, there is no attribute ‘class’, but rather an attribute called ‘dim’. Let’s use this for some manipulations. First we rip off the attribute:

Now we attach it again

That is, the attribute ‘class’ is not the only attribute to eventually set a class. Even more, let us now set an attribute class to the value ‘Date’:

So, if there is an attribute ‘class’ it overrides any secondary class affiliation