Extracting numbers from vectors of strings Extracting numbers from vectors of strings r r

Extracting numbers from vectors of strings


How about

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

or

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

or

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


UpdateSince extract_numeric is deprecated, we can use parse_number from readr package.

library(readr)parse_number(years)

Here is another option with extract_numeric

library(tidyr)extract_numeric(years)#[1] 20  1


I think that substitution is an indirect way of getting to the solution. If you want to retrieve all the numbers, I recommend gregexpr:

matches <- regmatches(years, gregexpr("[[:digit:]]+", years))as.numeric(unlist(matches))

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 of gregexpr and you can skip the unlist.