Skip to main content eteppo

Extract Percentages in Characters/Strings in R

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