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)
num
[1] 2.3 4.1 5.0 12.2
class(num)
"numeric"

The character type is also obvious – text:

chr = c("a", "b", "c")
chr
[1] "a" "b" "c"
class(chr)
[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)
fact
[1] 1 1 2 2 3 3
Levels: 1 2 3
class(fact)
[1] "factor"

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

fac = gl(3, 2, labels = c("p", "q", "r"))
fac
[1] p p q q r r
Levels: p q r
class(fac)
[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.

Advertisements

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