user1471980 user1471980 - 6 months ago 29
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?


How about

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


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


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