Reputation: 813
I've been trying to word this title for 5 minutes to avoid it being a similarly phrased question. No luck, so apologies if this has already been discussed. I couldn't find any other threads on this particular subject.
Simply put, I want to identify if numbers exist in a class character string. If true apply further functions.
Here's a dodgy attempt.
x <- "900 years old"
if(str_detect(x, ">=0")) {
print("contains numbers")
}
So obviously the problem is that I'm trying to use relational operators within a character string. Considering it's of this class, how can i identify numeric characters?
Upvotes: 1
Views: 1409
Reputation: 145755
[0-9]
is a regex pattern for numbers 0 to 9. You could also use special patterns \d
or [:digit:]
(for digits). In R, you have to add extra escapes to the special patterns. All of these should work:
str_detect(x, "[0-9]")
str_detect(x, "\\d")
str_detect(x, "[[:digit:]]")
Upvotes: 6