I have string like this:
years<-c("20 years old", "1 years old")
I would like to grep only the numeric number from this vector. Expected output is a vector:
c(20, 1)
How do I go about doing this?
I have string like this:
years<-c("20 years old", "1 years old")
I would like to grep only the numeric number from this vector. Expected output is a vector:
c(20, 1)
How do I go about doing this?
A
stringr
pipelined solution:Update Since
extract_numeric
is deprecated, we can useparse_number
fromreadr
package.Here is another option with
extract_numeric
I think that substitution is an indirect way of getting to the solution. If you want to retrieve all the numbers, I recommend
gregexpr
:If you have multiple matches in a string, this will get all of them. If you're only interested in the first match, use
regexpr
instead ofgregexpr
and you can skip theunlist
.