Objects and Classes

R is an object-oriented language. Every object in R has a type. Additionally, every object in R is a member of a class. We have already encountered several different classes: character vectors, numeric vectors, data frames, lists, and arrays.

You can use the class function to determine the class of an object. For example:

> class(teams)
[1] "character"
> class(w)
[1] "numeric"
> class(nleast)
[1] "data.frame"
> class(class)
[1] "function"

Notice the last example: a function is an object in R with the class function.

Some functions are associated with a specific class. These are called methods. (Not all functions are tied closely to a particular class; the class system in R is much less formal than that in a language like Java.)

In R, methods for different classes can share the same name. These are called generic functions. Generic functions serve two purposes. First, they make it easy to guess the right function name for an unfamiliar class. Second, generic functions make it possible to use the same code for objects of different types.

For example, + is a generic function for adding objects. You can add numbers together with the + operator:

> 17 + 6
[1] 23

You might guess that the addition operator would work similarly with other types of objects. For example, you can also use the + operator with a date object and a number:

> as.Date("2009-09-08") + 7
[1] "2009-09-15"

By the way, the R interpreter calls the generic function print on any object returned on the R console. ...

Get R in a Nutshell now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.