# load packages
library(tidyverse)

Here’s how to take care of the most common problems in coercing numbers that are characters in R into numeric format. The most common problems are

So we want to clean these two things up before we try coercing the number into numeric format using the as.numeric() function.

Let’s take a random number that has all of these problems.

" 174,872.44 " %>%
  # take out the commas
  str_remove_all(pattern = ",") %>%
  # take out any blank spaces before or after the number
  str_trim() %>%
  # coerce to numeric
  as.numeric()
## [1] 174872.4

Be lazy, make this into a function.

character_num_to_numeric <- function(character_num) {
  character_num %>%
  # take out the commas
  str_remove_all(pattern = ",") %>%
  # take out any blank spaces before or after the number
  str_trim() %>%
  # coerce to numeric
  as.numeric()
}

Make reproducible data for the example. Notice the number are characters.

example_tbl <- tribble(~type,      ~value,
                       "monkeys",  "4.2",
                       "wolves",   " 174,872.44 ")

example_tbl
clean_example_tbl <- example_tbl %>%
  mutate(value = character_num_to_numeric(value))

clean_example_tbl