Be classy: object class attributes in R

All R objects have a class attribute. This can be viewed (or set) via the class() command. The class can be any character string and an object can hold more than one class. You can use the class to help you identify what sort an object is, for example:

> bird
               Garden Hedgerow Parkland Pasture Woodland
Blackbird          47       10       40       2        2
Chaffinch          19        3        5       0        2
Great Tit          50        0       10       7        0
House Sparrow      46       16        8       4        0
Robin               9        3        0       0        2
Song Thrush         4        0        6       0        0

At first glance you cannot tell if this object is a data.frame or a matrix. The class() command can help you find out:

> class(bird)
[1] "matrix"

Some commands can be pressed into service for special classes – for example plot(), summary() and print() commands can be written to process objects of a specific class. You simply name your custom command to append the class; for example plot.lm(), print.lm() or summary.lm() commands, which are part of the basic distribution of R. When you issue a plot() command for example R looks at the class of the object to see if there is a plot.xxxx() command to match (where xxxx is the class of the object). If there is then this custom command is carried out. If a custom command is not available then the basic plot() command is used.

The class attribute is often used in functions to check that an object is of the right sort before carrying out the commands.

Comments are closed.