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.r113 chars4 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.r51 chars2 lines
gistlibby LogSnag