Get startedGet started for free

Assigning Classes

1. Assigning Classes

Previously, you saw the use of the class function to return the class of some R objects. The class function also has a second use, to override the class of an object. For example,

2. rexp()

you can take a numeric vector, in this case some random numbers from the exponential distribution then override the class to "random_numbers". Let's see what the x variable looks like now. The values of x are the same, but now x shows that it has an attribute named "class" with the value "random_numbers".

3. class()

Calling the class function on x like you did before, that is, without assignment, returns the value. Notice that the class of x doesn't tell us that x is numeric anymore. However, if you use typeof, the value is still the same. In fact, you can't override typeof: this is a fundamental property of an R object. Because of this, x is said to have an "implicit class" of "numeric". In practice, the best way to check that x is still a number would be

4. is.numeric()

to use the is-dot-numeric function. This function is smart enough to know that regardless of how the class value has changed, the variable still contains numbers. Similarly, the length function returns the correct value; we have 10 numbers here. Likewise, the mean function still calculates the mean of x correctly. In Chapter 2, you're going to see how to take advantage of being able to specify the class of an object. For now,

5. Summary

the important takeaways are that you can override the class, and that it is possible to do this without having to reinvent existing functionality. Everything continues to work as you need.

6. Let's practice!