I'm working with an arcane set of rounding rules that are similar to those implemented in base R only wrong. I need to round values to 2 significant figures using the "round to even" rule when the third digit is 5, but I need all of the digits to the right of the 5 to be ignored when making this determination. Here is a minimal example.
What R does:
> signif(2059, 2)
[1] 2100
Behavior I want:
> signif(2059, 2)
[1] 2000
I tried to think of ways to do this with the functions I'm aware of, but came up blank. Something with str_sub might work to replace every digit after the 5 with a 0, but not all the numbers I'm working with have the same number of digits and I'm not sure how to deal with that when it comes to the replacement part of the function.
Edit: here is an expanded example, with the differences marked with an asterisk.
What R does:
x <- c(25, 211, 215, 216, 2250, 2251, 2350, 2359, 24500, 24563)
signif(x, 2)
 [1]    25   210   220   220  2200  2300  2400  2400 24000 25000
What I want:
x <- c(25, 211, 215, 216, 2250, 2251, 2350, 2359, 24500, 24563)
signif(x, 2)
 [1]    25   210   220   220  2200  *2200  2400  2400 24000 *24000
Maybe you can use %/% and log10 to cut of the right numbers?
x <- c(25, 211, 215, 216, 2250, 2251, 2350, 2359, 24500, 24563, 0)
signifIncorect <- function(x, digits = 2) {
  n <- ceiling(log10(abs(x)))
  y <- 10^(n - 1 - digits)
  replace(round(x %/% y * y, digits - n), x==0, 0)
}
signifIncorect(x, 2)
# [1]    25   210   220   220  2200  2200  2400  2400 24000 24000     0
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With