0

parse_number has been the perfect function for when I am parsing html tables that have columns formatted with "%". Very often, I want to use parse_number and convert to a decimal in one whole operation. I know there are alternate ways to parse the function without using parse-number, but does parse_number have a way to do what I'm looking for built into the function? Otherwise, most of my mutate_at commands end up getting run in two separate operations.

Sample code below:

library(readr)

x <- "10.5%"

parsed <- parse_number(x)

parsed_decimal <- parsed / 100
Jazzmatazz
  • 615
  • 7
  • 18
  • 2
    You could directly do `parse_number(x)/100` ? Also here are variety of options https://stackoverflow.com/questions/8329059/how-to-convert-character-of-percentage-into-numeric-in-r – Ronak Shah Jun 19 '19 at 01:55

1 Answers1

1

Why not just write your own function:

x <- "10.5%"
y <- c("9.0%", "8.3%", "51.2%")

parse_pct <- function(x) {
    parsed <- readr::parse_number(x)
    parsed_decimal <- parsed / 100
    parsed_decimal
}

parse_pct(x)
#> [1] 0.105
purrr::map_dbl(y, parse_pct)
#> [1] 0.090 0.083 0.512

Created on 2019-06-18 by the reprex package (v0.3.0)

N. Williams
  • 175
  • 11
  • 1
    The function is a good idea, but you've written a vectorised function so no need to map over it and introduce another dependency in purrr. Just `parse_pct(y)` does it. – thelatemail Jun 19 '19 at 05:03