Code
library(purrr)
options(scipen = 999)
set.seed(0)
July 20, 2024
To improve the readability of a table, I wanted to round various numbers between 100 and 10,000,000 to their first two digits. 123,456 would become 120,000 and 987 would become 990.
Here is the solution I came up with.
\[ \text{scale} \leftarrow 10^{\lceil \log_{10}(x) \rceil} \]
\[ \text{round}\left(\frac{x}{\text{scale}}, 2\right) \times \text{scale} \]
round_first_two <- function(x) {
scale <- 10^ceiling(log10(x))
round(x / scale, 2) * scale
}
x1 <- c(113, 2795, 42459, 442060, 6870466)
x1
[1] 113 2795 42459 442060 6870466
[1] 110 2800 42000 440000 6900000
GitHub Copilot suggested a more general solution that works for numbers smaller and equal to zero.
[1] 113 -2795 -42459 -442060 6870466 0
[1] 110 NaN NaN NaN 6900000 NaN
round_first_two_digits <- function(x) {
if (x == 0) {
return(0)
}
num_digits <- floor(log10(abs(x))) + 1
scale_factor <- 10^(num_digits - 2)
round(x / scale_factor) * scale_factor
}
x2
[1] 113 -2795 -42459 -442060 6870466 0
[1] 110 -2800 -42000 -440000 6900000 0