12.07.2015 Views

R dummies

R dummies

R dummies

SHOW MORE
SHOW LESS
  • No tags were found...

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

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

Converting a factorSometimes you need to explicitly convert factors to either text or numbers. Todo this, you use the functions as.character() or as.numeric().First, convert your directions vector into a factor called directions.factor(as you saw earlier):> directions directions.factor directions.factor[1] North East South SouthLevels: East North SouthUse as.character() to convert a factor to a character vector:> as.character(directions.factor)[1] “North” “East” “South” “South”Use as.numeric() to convert a factor to a numeric vector. Note that this willreturn the numeric codes that correspond to the factor levels. For example, “East”corresponds to 1, “North” corresponds to 2, and so forth:> as.numeric(directions.factor)[1] 2 1 3 3Be very careful when you convert factors with numeric levels to a numericvector. The results may not be what you expect.For example, imagine you have a vector that indicates some test score resultswith the values c(9, 8, 10, 8, 9), which you convert to a factor:> numbers str(numbers)Factor w/ 3 levels “8”,”9”,”10”: 2 1 3 1 2This indicates that R stores the values as c(2, 1, 3, 1, 2) with associatedlevels of c(“8”, “9”, “10”). Figure 5-2 gives a graphical representation of this

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

Saved successfully!

Ooh no, something went wrong!