How do I get numbers from character vectors in R?
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 to share