![]() |
VOOZH | about |
In this article, we are going to see how to extract Numbers from Character String Vector in R Programming Language. There are different approaches to extract numbers from character string vectors using some in-built functions. It can be done in the following ways:
gsub() function in R is used to replace patterns in a string. It can also be employed to extract numbers from a string by defining a pattern to capture the number and returning it.
gsub(pattern, replacement, x, ignore.case = FALSE, perl = FALSE,fixed = FALSE, useBytes = FALSE)
Parameters:
Steps:
Example:
Output:
[1] "7g8ee6ks1" "5f9o1r0" "geeks10"
[1] 7 5 10
Explanation: gsub() captures the first occurrence of digits in each string and returns the numbers as a numeric vector. In this case, it captures 7, 5, and 10 from the strings "7g8ee6ks1", "5f9o1r0", and "geeks10".
In this method, we use gregexpr() to identify all the positions of the numbers in the strings, and regmatches() to extract those numbers. This approach is useful when you want to extract multiple numbers from a single string.
gregexpr() function: The gregexpr() function searches for patterns in a string and returns the positions of all matches.
gregexpr(pattern, text, ignore.case = FALSE, perl = FALSE, fixed = FALSE, useBytes = FALSE)
Parameters:
pattern: The regular expression to match.regmatches() function: This function is used to extract or replace matched sub-strings from match data.
regmatches(x, m, invert = FALSE)
Parameters:
Example:
Output:
[1] 7 8 6 1 5 9 1 0 10