Convert Discrete Factor to Continuous Variable in R (Example)


This tutorial shows how to change a discrete variable to a continuous variable in R programming.

The post looks as follows:

Let’s dive right into the programming part…


Creation of Example Data

The first step is to construct some data that we can use in the following examples:

x <- factor(c(1, 5, 2, 7, 4, 4, 1))      # Create example factor
x                                        # Print example factor
# [1] 1 5 2 7 4 4 1
# Levels: 1 2 4 5 7

Have a look at the previous output of the RStudio console. It shows that our example data is a factor vector (i.e. a discrete variable) containing seven elements.


Example: Treat Discrete Factor Levels as Continuous Data Using as.character() & as.numeric() Functions

This section illustrates how to convert a discrete factor variable to a continuous data object in R.

For this task, we have to apply the as.numeric and as.character functions as shown below:

x_cont <- as.numeric(as.character(x))    # Convert factor to numeric
x_cont                                   # Print numeric variable
# [1] 1 5 2 7 4 4 1

As you can see based on the previous output of the RStudio console, our new vector contains the same numbers as the input factor vector. However, this time the factor levels are not shown anymore, because our new vector has the numeric class.

We can also check that by applying the class function to this new vector:

class(x_cont)                            # Check class of updated data
# [1] "numeric"

The RStudio console tells us what we already know: Our updated variable has the numeric class, i.e. it is a continuous variable.


Video & Further Resources

Have a look at the following video that I have published on my YouTube channel. In the video, I’m explaining the R codes of this article in the R programming language:



In addition, you may want to read the other posts on this website:


To summarize: This tutorial has explained how to set a discrete categorical variable to a continuous variable in R programming.

In this tutorial, we have converted a discrete vector object to a continuous variable. Note that we could apply the same syntax to a data frame column as well.

If you have further questions, let me know in the comments section. Besides that, please subscribe to my email newsletter in order to get updates on the newest articles.


Subscribe to the Statistics Globe Newsletter

Get regular updates on the latest tutorials, offers & news at Statistics Globe.
I hate spam & you may opt out anytime: Privacy Policy.

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.