Types of R object – basics

Types of R object

R “recognises” various sorts of object. Every object holds a class attribute, which controls how the object is dealt with by various commands.

At the most basic level you can think of R objects as being in one of three main forms:

  • numeric
  • character
  • factor

Object type: basics

The numeric type is obvious – numbers:

num = c(2.3, 4.1, 5, 12.2)
[1] 2.3 4.1 5.0 12.2

The character type is also obvious – text:

chr = c("a", "b", "c")
[1] "a" "b" "c"
[1] "character"

The last basic type is a factor.  The factor can appear like a number or a character, depending upon its contents:

fact = gl(3, 2)
[1] 1 1 2 2 3 3
Levels: 1 2 3
[1] "factor"

The previous object (fact) looks like numbers. The following looks superficially like characters:

fac = gl(3, 2, labels = c("p", "q", "r"))
[1] p p q q r r
Levels: p q r
[1] "factor"

In fact, you can see that it is not a character object because the text items do not have quotes around them. Another “clue” is the Levels: part of the display – but beware because this is not always displayed.

Factor objects are important and are used in many statistical analyses. When you import data using read.csv() for example, the columns of text are converted to factor objects unless you explicitly tell R otherwise.


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s