Convert Factor to Numeric in R (Example)

This tutorial explains how to convert a factor vector to numeric in the R programming language.

Example Vector

vec <- as.factor(c("5", "2", "2", "7", "5"))   # Create factor vector
vec                                            # Print example vector
# [1] 5 2 2 7 5
# Levels: 2 5 7

Conversion of Factor to Numeric

The following R code converts our example vector from factor to numeric in R. Note that we need to convert the factor to character with the as.character() function first, before we can convert the character to numeric. If we don’t perform this step in between, we would lose the factor levels.

vec_num <- as.numeric(as.character(vec))       # Convert factor to numeric
vec_num                                        # Print updated vector
# 5 2 2 7 5

Video Examples

The following video of the Statistics Globe YouTube channel explains how to change characters and factors to numeric:

You are currently viewing a placeholder content from YouTube. To access the actual content, click the button below. Please note that doing so will share data with third-party providers.

More Information

Leave a Reply

Your email address will not be published. Required fields are marked *

Fill out this field
Fill out this field
Please enter a valid email address.
You need to agree with the terms to proceed

Menu
Top