Skip to content

Instantly share code, notes, and snippets.

@jhrcook
Created May 26, 2020 11:43
Show Gist options
  • Save jhrcook/993a3dd58d5e9f970facbfbadfd0930d to your computer and use it in GitHub Desktop.
Save jhrcook/993a3dd58d5e9f970facbfbadfd0930d to your computer and use it in GitHub Desktop.
A function for parsing ounces into a numeric value.
# Parse a string given in "# #/# oz" into a decimal value.
parse_ounces <- function(val) {
if (val == "For glass") { return(1) }
if (str_detect(val, "or")) {
val <- str_remove(val, "or.+$")
}
val_pieces <- str_remove_all(val, "oz|slices|tsp|dash") %>%
str_trim() %>%
str_split(" ") %>%
unlist() %>%
str_trim()
val_pieces <- val_pieces[str_length(val_pieces) > 0]
map_dbl(val_pieces, function(x){
if (str_detect(x, "/")) {
x_frac <- str_split(x, "/") %>% unlist() %>% as.numeric()
return(x_frac[[1]] / x_frac[[2]])
} else {
return(as.numeric(x))
}
}) %>%
sum()
}
test_that("The ounces are parsed correctly.", {
expect_equal(parse_ounces("1 oz"), 1)
expect_equal(parse_ounces("1/2 oz"), 0.5)
expect_equal(parse_ounces("1 1/2 oz"), 1.5)
expect_equal(parse_ounces("For glass"), 1)
expect_equal(parse_ounces("1/2 or 1"), 0.5)
expect_equal(parse_ounces("1 3/4 oz"), 1.75)
expect_equal(parse_ounces("1 dash"), 1)
})
@jhrcook
Copy link
Author

jhrcook commented May 26, 2020

Some editorial decisions were made on what to do with other units including "slices," "tsp," and "dash." Any differences were just ignored for my purposes.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment