regex number in r

To regex number in R, we can use the grep or grepl function. The grep function returns the index of the matching elements, while the grepl function returns a logical vector indicating whether there is a match or not.

For example, to find all elements that contain a number in a character vector x, we can use the following regex pattern:

main.r
x <- c("abc123", "def", "456xyz")
grep("[0-9]", x) # returns 1 and 3
grepl("[0-9]", x) # returns TRUE TRUE FALSE
113 chars
4 lines

The regex pattern [0-9] matches any digit between 0 and 9. Note that we need to use the square brackets to specify the character set we want to match.

We can also use the sub or gsub function to replace the matched patterns with a different string. For example, to remove all digits from the elements in x, we can use:

main.r
gsub("[0-9]", "", x) # returns "abc", "def", "xyz"
51 chars
2 lines

gistlibby LogSnag