25.7 Other vector functions

Here, we want to strip percent signs, commas, and dollar signs from a string before converting it into a number:

# https://twitter.com/NVlabormarket/status/1571939851922198530

clean_number <- function(x) {
  is_pct <- str_detect(x, "%")
  num <- x |> 
    str_remove_all("%") |> 
    str_remove_all(",") |> 
    str_remove_all(fixed("$")) |> 
    as.numeric(x)
  if_else(is_pct, num / 100, num)
}

clean_number("$12,300")
## [1] 12300
clean_number("45%")
## [1] 0.45