How to Extract Numeric Values from Vector of Character Strings in R (Example Code)

In this R programming tutorial you’ll learn how to return numeric values from a vector of character strings.

Creation of Example Data

my_string <- c("XXX555XXX111", "sdhgf1skjdfh2", "X3", "Z7")                      # Example character vector
my_string                                                                        # Returning character vector to console
# "XXX555XXX111"  "sdhgf1skjdfh2" "X3"            "Z7"

Example: Returning All Numeric Values from Character String

my_string_numbers <- regmatches(my_string, gregexpr("[[:digit:]]+", my_string))  # Using gregexpr & regmatches functions
my_string_numbers                                                                # Returning list with numeric values
# [[1]]
# [1] "555" "111"
# 
# [[2]]
# [1] "1" "2"
# 
# [[3]]
# [1] "3"
# 
# [[4]]
# [1] "7"
as.numeric(unlist(my_string_numbers))                                            # Converting list with characters to numeric vector
# 555 111   1   2   3   7

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

Menu
Top