regex all numbers in r

To regex all numbers in R, you can use the gsub() function and a regular expression pattern to replace all non-numeric characters with an empty string. Here's an example:

main.r
# create a vector of strings with numbers and non-numeric characters
strings <- c("123", "45.6", "7a8b9", "$10,000")

# use gsub() to remove all non-numeric characters
numeric_strings <- gsub("[^[:digit:]]", "", strings)

# print the results
print(numeric_strings)
265 chars
9 lines

Output:

main.r
[1] "123"     "456"     "789"     "10000"
42 chars
2 lines

This will remove all non-numeric characters from the strings vector, leaving only the numeric strings. The regular expression pattern "[^[:digit:]]" matches any character that is not a digit, and the gsub() function replaces each of these characters with an empty string.

gistlibby LogSnag