10.07.2015 Views

Using R for Introductory Statistics : John Verzani

Using R for Introductory Statistics : John Verzani

Using R for Introductory Statistics : John Verzani

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Multivariate data 133When a factor is printed, the levels also appear.It is important to realize that these are factors and not numbers. For example, we can’tadd factors.> x + factor(x)[1] NA NA NAWarning message:"+" not meaningful <strong>for</strong> factors in: Ops.factor(x,factor(x))Adding levels: levels=and levels()When defining a factor, the levels= argument can be used to specify the levels.> factor(x,levels=1:10) # add more levels than 3[1] 1 2 3Levels: 1 2 3 4 5 6 7 8 9 10> factor(x,levels=fac) # get NA if not in levels[1] Levels: a b cThe values of data vector being coerced into a factor should match those specified tolevels=.The levels() function can list the levels of a factor directly and allows us to change oradd to the levels.> x = factor(1:5)> x[1] 1 2 3 4 5Levels: 1 2 3 4 5> levels(x) # character vector[1] "1" "2" "3" "4" "5"The levels() function can also change the levels of a factor. As levels() changes anattribute of the data vector, like names(), it appears on the other side of the assignment.For example:> x = factor(1:3)> x[1] 1 2 3Levels: 1 2 3> levels(x) = letters [1:3]> x[1] a b cLevels: a b c> levels(x) = 1:10 # add morelevels> x[1] 1 2 3Levels: 1 2 3 4 5 6 7 8 9 10

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!