Skip to main content eteppo

Extract The First Number in A String/Character in R

Published: 2023-08-04
Updated: 2023-08-04
trim_to_1st_number <- function(x) {
  assert_that(is.character(x))
  assert_that(length(x) > 0)
  detect_number <- function(x) {
    str_detect(x, "\d+")
  }
  extract_number <- function(x) {
    str_extract(x, "\d+[:punct:]*\d*")
  }
  unlist(purrr::map_if(x, detect_number, extract_number))
}