Sometimes you need to explicitly convert factors to either text or numbers. To do this, you use the functions
as.numeric(). First, convert your data vector into a factor or use existed factors
iris$Species from iris dataset.
v = c("North", "East", "South", "South") vf <- factor(v)
as.character() to convert a factor to a character vector
as.numeric() to convert a factor to a numeric vector. Note that this will return the numeric codes that correspond to the factor levels.
as.numeric(vf) # or from iris dataset as.numeric(factor(iris$Species))
Be very careful when you convert factors with numeric levels to a numeric vector. The results may not be what you expect.
For example, imagine you have a vector that indicates some test score results with the values
c(9, 8, 10, 8, 9), which you convert to a factor
numbers = factor(c(9, 8, 10, 8, 9))
To look at the internal representation of numbers, use
This indicates that R stores the values as
c(2, 1, 3, 1, 2) with associated levels of
c("8", "9", "10").