Convert Factor to Numeric With the as.numeric Function in R

Use the
as.numeric
Function to Convert Factor to Numeric in R 
Combine
as.character
andas.numeric
Functions to Convert Factor to Numeric in R
This article will demonstrate multiple methods about how to convert factor to numeric in R.
Use the as.numeric
Function to Convert Factor to Numeric in R
The as
functions are generally used to convert data type to another type explicitly. The conversion process is called coercion in R terminology, and it denotes the concept of casting present in other programming languages. When we call to function as.logical
, it tries to coerce the passed argument to the logical type. Similarly, as.character
and as.numeric
convert the given arguments to the corresponding types. Notice that any number (except zero) converted to the logical type represents a TRUE
value, even negatives.
> as.logical(31)
[1] TRUE
> as.logical(31)
[1] TRUE
> as.character(31)
[1] "31"
> as.numeric(FALSE)
[1] 0
> as.numeric(TRUE)
[1] 1
R also implements implicit type coercion rules, which are needed when arithmetic operations are done on the vectors consisting of different types. As demonstrated in the following code snippet, if an atomic vector contains a character string, every other element is converted to the string as well. If the vector includes mixed elements of logic, numbers, and strings, they are coerced to string types. Finally, when the vector contains numbers and logic, the latter ones are converted to numbers.
> v1 < c(1, "two", 3, 4, 5, 6)
> typeof(v1)
[1] "character"
> v1 < c(T, "two", 3, 1, F, T)
> typeof(v1)
[1] "character"
> v1 < c(1, T, 3, F, 5, 6)
> typeof(v1)
[1] "double"
When converting a factor to numeric, it’s important to note that as.numeric
will only return the underlying integer representation, which is mostly meaningless and does not correspond to the factor levels. One can examine how a factor object is stored internally using the unclass
function. Notice that the f2
factor has an index of 2 1 2 3
, which is generally returned using the as.number
call as shown in the next code sample:
> f2 < factor(c(3, 2, 3, 4))
> f2
[1] 3 2 3 4
Levels: 2 3 4
> f2.n < as.numeric(f2)
> unclass(f2)
[1] 2 1 2 3
attr(,"levels")
[1] "2" "3" "4"
> f2.n
[1] 2 1 2 3
Combine as.character
and as.numeric
Functions to Convert Factor to Numeric in R
The factor levels can be converted to the integer type by combining as.character
and as.numeric
functions. as.character
returns factor levels as character strings. Then we can call the as.numeric
function to coerce string to numbers.
> f2 < factor(c(3, 2, 3, 4))
> f2.c < as.character(f2)
> f2.c
[1] "3" "2" "3" "4"
> f2.c < as.numeric(as.character(f2))
> f2.c
[1] 3 2 3 4