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
:
n <- 10:14
n
#> [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
):
# Numeric to Character
c <- as.character(n)
# Numeric to Factor
f <- factor(n)
# 10 11 12 13 14
To convert the character vector to the other two:
# Character to Numeric
as.numeric(c)
#> [1] 10 11 12 13 14
# Character to Factor
factor(c)
#> [1] 10 11 12 13 14
#> Levels: 10 11 12 13 14
Converting a factor to a character vector is straightforward:
# Factor to Character
as.character(f)
#> [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.
as.numeric(f)
#> [1] 1 2 3 4 5
# Another way to get the numeric coding, if that's what you want:
unclass(f)
#> [1] 1 2 3 4 5
#> attr(,"levels")
#> [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.
# Factor to Numeric
as.numeric(as.character(f))
#> [1] 10 11 12 13 14