Convert Data Frame Column to Numeric in R (2 Examples)

The following R codes show how to convert data frame columns to numeric in the R programming language.

Example Data Frame

my_data <- data.frame(char = c("3", "75", "10", "8"),        # Create example data
                      fact = factor(c("3", "1", "5", "5")),
                      stringsAsFactors = FALSE)
my_data                                                      # Print data to console
# char fact
#    3    3
#   75    1
#   10    5
#    8    5

Check data classes of our two columns:

class(my_data$char)                                          # Check class of first column
# "character"

class(my_data$fact)                                          # Check class of second column
# "factor"

Example 1: Conversion of Character Column to Numeric

my_data$char <- as.numeric(my_data$char)                     # Character column to numeric

Check updated class of character column:

# "numeric"

Example 2: Conversion of Factor Column to Numeric

my_data$fact <- as.numeric(as.character(my_data$fact))       # Factor column to numeric

Check updated class of factor column:

# "numeric"

Live Example: How to Convert Data Frame Variables to Numeric


By loading the video, you agree to YouTube’s privacy policy.
Learn more

Load video

Leave a Reply

Your email address will not be published.

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