Home » How to Convert Factor to Numeric in R (With Examples)

How to Convert Factor to Numeric in R (With Examples)

by Erma Khan
spot_img

We can use the following syntax to convert a factor vector to a numeric vector in R:

numeric_vector numeric(as.character(factor_vector))

We must first convert the factor vector to a character vector, then to a numeric vector. This ensures that the numeric vector contains the actual numeric values instead of the factor levels.

This tutorial provides several examples of how to use this function in practice.

Example 1: Convert a Vector from Factor to Numeric

The following code shows how to convert a factor vector to a numeric vector:

#define factor vector
factor_vector 
#convert factor vector to numeric vector
numeric_vector numeric(as.character(factor_vector))

#view class
class(numeric_vector)

[1] "numeric"

Example 2: Convert a Column from Factor to Numeric

The following code shows how to convert a specific column in a data frame from factor to numeric:

#create data frame
df frame(a = factor(c(1, 5, 7, 8)),
                 b = c(28, 34, 35, 36))

#convert column 'a' from factor to numeric
df$a numeric(as.character(df$a))

#view new data frame
df

  a  b
1 1 28
2 5 34
3 7 35
4 8 36

#confirm class of numeric vector
class(df$a)

[1] "numeric"

Example 3: Convert Several Columns from Factor to Numeric

The following code shows how to convert all factor columns in a data frame from factor to numeric:

#create data frame
df frame(a = factor(c(1, 5, 7, 8)),
                 b = factor(c(2, 3, 4, 5)),
                 c = c('A', 'B', 'C', 'D'),
                 d = c(45, 56, 54, 57))

#display classes of each column
sapply(df, class)

       a           b           c           d 
"factor"    "factor" "character"   "numeric" 

#identify all factor columns
x sapply(df, is.factor)

#convert all factor columns to numeric
df[ , x] data.frame(apply(df[ , x], 2, as.numeric))

#display classes of each column
sapply(df, class)

        a           b           c           d 
"numeric"   "numeric" "character"   "numeric" 

This code made the following changes to the data frame columns:

  • Column a: From factor to numeric
  • Column b: From factor to numeric
  • Column c: Unchanged (since it was a character)
  • Column d: Unchanged (since it was already numeric)

By using the apply() and sapply() functions, we were able to convert only the factor columns to numeric columns and leave all other columns unchanged.

Additional Resources

How to Convert Character to Factor in R
How to Convert Factor to Character in R
How to Convert a Character to a Timestamp in R

spot_img

Related Posts