Created
March 5, 2024 14:31
-
-
Save martinctc/4e9de2911ce8a69dd66ba6e1bc88b361 to your computer and use it in GitHub Desktop.
[Convert numeric value to natural language approximation] #R
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#' @title Convert a numeric value into a natural language approximation string | |
#' | |
#' @description | |
#' This function takes a numeric value and returns a string that approximates the value in natural language. | |
#' | |
#' @param x A numeric value. | |
#' | |
#' @examples | |
#' approx_num(0.5) | |
#' # [1] "increased by a half" | |
#' | |
#' approx_num(1.35) | |
#' # [1] "increased by about 140%" | |
#' | |
#' @return | |
approx_num <- function(x){ | |
xrnd1 <- round(x, 0) | |
xrnd2 <- round(x*2,0)/2 | |
xrnd3 <- round(x*3,0)/3 | |
xrnd4 <- round(x*4,0)/4 | |
xrnd10 <- round(x*10,0)/10 | |
xrnd100 <- round(x*100,0)/100 | |
approx <- dplyr::case_when( | |
x == -1 ~ paste0("decreased to zero"), | |
x <= -0.95 ~ paste0("decreased to near zero"), | |
x < -0.2 ~ paste0("decreased by about ", abs(xrnd10)*100, "%"), | |
x < -0.1 ~ paste0("decreased slightly by ", abs(xrnd10)*100, "%"), | |
x < 0.1 ~ paste0("overall did not significantly increase or decrease"), | |
xrnd4*4 == 1 & abs(xrnd4 - x) <= abs(xrnd3-x) ~ | |
case_when( | |
xrnd4 > x ~ "increased by almost a quarter", | |
xrnd4 == x ~ "increased by a quarter", | |
xrnd4 < x ~ "increased by more than a quarter"), | |
xrnd3*3 == 1 & abs(xrnd3 - x) <= abs(xrnd2-x) ~ | |
case_when( | |
xrnd3 > x ~ "increased by almost a third", | |
xrnd3 == x ~ "increased by a third", | |
xrnd3 < x ~ "increased by more than a third"), | |
xrnd2*2 == 1 ~ | |
case_when( | |
xrnd2 > x ~ "increased by almost half", | |
xrnd2 == x ~ "increased by a half", | |
xrnd2 < x ~ "increased by more than half"), | |
x < 0.85 ~ paste0("increased by about", xrnd10*100, "%"), | |
xrnd1 == xrnd2 ~ | |
case_when( | |
xrnd2 > x ~ paste0("increased by almost ", xrnd2+1, "X"), | |
xrnd2 == x ~ paste0("increased by ", xrnd2+1, "X"), | |
xrnd2 < x ~ paste0("increased by more than ", xrnd2+1, "X")), | |
TRUE ~ paste0("increased by about ", xrnd10*100, "%") | |
) | |
return(approx) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment