user1471980 user1471980 - 2 months ago 7
R Question

Extracting numbers from vectors of strings

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?

Answer

How about

# pattern is by finding a set of numbers in the start and capturing them
as.numeric(gsub("([0-9]+).*$", "\\1", years))

or

# pattern is to just remove _years_old
as.numeric(gsub(" years old", "", years))

or

# split by space, get the element in first index
as.numeric(sapply(strsplit(years, " "), "[[", 1))