# How to Convert a Factor to Numeric in R

**Basic R Syntax:**

x_num <- as.numeric(as.character(x)) |

x_num <- as.numeric(as.character(x))

More explanations needed? You’ll find all relevant information for the **conversion of R factors to numeric** in the following tutorial.

## Example: Convert Factor to Numeric in R

To convert a factor to numeric in R can be a tricky task. In the following, I’m therefore going to explain how to convert a factor vector to numeric properly.

Before we can start, we need to create an **example factor vector in R**:

set.seed(13579) # Set seed x <- as.factor(sample(c(3, 5, 6, 9), 100, replace = TRUE)) # Example factor vector |

set.seed(13579) # Set seed x <- as.factor(sample(c(3, 5, 6, 9), 100, replace = TRUE)) # Example factor vector

Our factor vector consists of the four categories 3, 5, 6 & 9:

`x # Print x to RStudio console` |

x # Print x to RStudio console

Graphic 1: Example Factor Vector Printed to the RStudio Console

So, how can we transform this factor vector to numeric?

x_num <- as.numeric(as.character(x)) # Convert factor to numeric x_num # Print converted x to RStudio console # 3 9 3 9 5 5 3 9 9 3 9 9 9... |

x_num <- as.numeric(as.character(x)) # Convert factor to numeric x_num # Print converted x to RStudio console # 3 9 3 9 5 5 3 9 9 3 9 9 9...

That’s it! Easy, right?

However, please note that – before the conversion to numeric – it is important to transform the **factor to character** first (as shown in the example above).

I’ll show you why this preliminary step is needed:

x_wrong <- as.numeric(x) # Wrong conversion to numeric x_wrong # Print wrongly converted x to RStudio console # 1 4 1 4 2 2 1 4 4 1 4 4 4... |

x_wrong <- as.numeric(x) # Wrong conversion to numeric x_wrong # Print wrongly converted x to RStudio console # 1 4 1 4 2 2 1 4 4 1 4 4 4...

1? 4?! 22??? What happened?! Why does the converted vector consist of **wrong values**?

The answer is simple: R automatically assigns the numbers 1, 2, 3, 4, and so on to the categories of our factor. If we want to hinder R from doing so, we need to convert the factor to character first.

Keep this in mind, when you convert a factor vector to numeric! I’ve seen this mistake quite often in the past.

## Programming Video: Further Examples

Check out the following video, in case you need **further explanations and examples** for the transformation of factors to numerical vectors. The YouTuber Phil Chan provides a live example in R.

## Alternative Programming Codes

I’ve shown you the **most popular way** to convert factor to numeric in R. However, there are several alternative ways to achieve this transformation:

**Alternative 1: The levels R function**

x_alt1 <- as.numeric(levels(x)[x]) # Use the levels R function x_alt1 # Print to R console |

x_alt1 <- as.numeric(levels(x)[x]) # Use the levels R function x_alt1 # Print to R console

**Alternative 2: The paste R function**

x_alt2 <- as.numeric(paste(x)) # Use the paste R function x_alt2 # Print to R console |

x_alt2 <- as.numeric(paste(x)) # Use the paste R function x_alt2 # Print to R console

**Alternative 3: The unfactor R function of the varhandle package**

install.packages("varhandle") # Install varhandle package library("varhandle") # Load varhandle package x_alt3 <- unfactor(x) # Use the unfactor R function x_alt3 # Print to R console |

install.packages("varhandle") # Install varhandle package library("varhandle") # Load varhandle package x_alt3 <- unfactor(x) # Use the unfactor R function x_alt3 # Print to R console

## Further Reading

### Subscribe to my free statistics newsletter:

### R Tutorials

abs Function in R

all & any R Functions

Set Aspect Ratio of Plot

attach & detach R Functions

attr, attributes & structure in R

cbind R Command

Change ggplot2 Legend Title

Character to Numeric in R

Check if Object is Defined

col & row sums, means & medians

Complete Cases in R

Concatenate Vector of Strings

Convert Date to Weekday

cumsum R Function

Data Frame Column to Numeric

diff Command in R

difftime R Function

dim Function in R

dir R Function

Disable Scientific Notation

Draw Segments in R

droplevels R Example

Evaluate an Expression

Extract Characters from String

Factor to Numeric in R

Format Decimal Places

get, get0 & mget in R

is.na R Function

is.null Function in R

jitter R Function

Join Data with dplyr Package

length Function in R

lowess R Smoothing Function

max and min Functions in R

NA Omit in R

nchar R Function

ncol Function in R

nrow Function in R

outer Function in R

pairs & ggpairs Plot

parse, deparse & R expression

paste & paste0 Functions in R

pmax and pmin R Functions

polygon Plots in R

pretty R Function

R Find Missing Values

R Functions List (+ Examples)

R NA – Values

R Replace NA with 0

rbind & rbind.fill in R

Read Excel Files in R

readLines, n.readLines & readline

Remove Element from List

Remove Legend in ggplot2

Rename Column Name in R

Replace Last Comma of String

rev R Command

Round Numeric Data in R

Save & Load RData Workspace

scan R Function

setdiff R Function

setNames vs. setnames in R

sink Command in R

Sort, Order & Rank Data in R

sprintf Function in R

Square Root in R

str_c Function of stringr Package

str_sub Function of stringr Package

strptime & strftime Functions

substr & substring R Commands

sweep R Function

Transform Data Frames

union Function in R

unlist in R

weekdays, months, quarters & julian in R

with & within R Functions

Write Excel File in R