How do I get numbers from character vectors in R?

I have a vector character and you want to get numbers from it both integers and floats.

    a<- c("Sam is 5 years old", "Ram is 3.7 years old" , "John is 17 years 2 months old")

      

the output should be

      [1]  5  3.7 17.2

      

+3


source to share


2 answers


We can use parse_number

fromreadr

readr::parse_number(a)
#[1]  5.0  3.7 17.0

      

Update

Based on OP's new example



library(stringr)
sapply(str_extract_all(a, "[0-9]+\\s+(years|months)"), function(x) {
       x1 <- readr::parse_number(x)
       head(if(length(x1)==2)   x1 + round(x1[2]/12, 1) else x1, 1)})
#[1]  5.0  7.0 17.2

      

If we don't need to worry about dividing by 12 months, another option is

as.numeric(sapply(regmatches(a, gregexpr('[0-9]+', a)), paste, collapse="."))
#[1]  5.0  3.7 17.2

      

+4


source


Here is one liner,



as.numeric(gsub(' ', '.', trimws(gsub('\\D+', ' ', a))))
#[1]  5.0  3.7 17.2

      

+2


source







All Articles