Converting between vector types

Problem

You want to convert between numeric vectors, character vectors, and factors.

Solution

Suppose you start with this numeric vector n:

  1. n <- 10:14
  2. n
  3. #> [1] 10 11 12 13 14

To convert the numeric vector to the other two types (we’ll also save these results in c and f):

  1. # Numeric to Character
  2. c <- as.character(n)
  3. # Numeric to Factor
  4. f <- factor(n)
  5. # 10 11 12 13 14

To convert the character vector to the other two:

  1. # Character to Numeric
  2. as.numeric(c)
  3. #> [1] 10 11 12 13 14
  4. # Character to Factor
  5. factor(c)
  6. #> [1] 10 11 12 13 14
  7. #> Levels: 10 11 12 13 14

Converting a factor to a character vector is straightforward:

  1. # Factor to Character
  2. as.character(f)
  3. #> [1] "10" "11" "12" "13" "14"

However, converting a factor to a numeric vector is a little trickier. If you just convert it with as.numeric, it will give you the numeric coding of the factor, which probably isn’t what you want.

  1. as.numeric(f)
  2. #> [1] 1 2 3 4 5
  3. # Another way to get the numeric coding, if that's what you want:
  4. unclass(f)
  5. #> [1] 1 2 3 4 5
  6. #> attr(,"levels")
  7. #> [1] "10" "11" "12" "13" "14"

The way to get the text values converted to numbers is to first convert it to a character, then a numeric vector.

  1. # Factor to Numeric
  2. as.numeric(as.character(f))
  3. #> [1] 10 11 12 13 14