How to convert a factor to numeric in R

Sometimes you need to explicitly convert factors to either text or numbers. To do this, you use the functions as.character() or 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)

Use as.character() to convert a factor to a character vector

as.character(vf)

Use 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 str()

str(numbers)

This indicates that R stores the values as c(2, 1, 3, 1, 2) with associated levels of c("8", "9", "10").

comments powered by Disqus