round_smart.Rd
This function automatically rounds numbers so that the results have as few digits as possible, but as many as necessary/desired. It is similar to signif()
, but it never alters the part before the decimal separator and also allows a cutoff value for a maximum acceptable number of digits after the decimal separator.
round_smart(x, signif_digits = 1, max_digits = 6)
A number of vector of numbers
The number of significant digits (default: 1) like in signif()
, but only applied to the part after the decimal separator.
round_smart(1.0001234, signif_digits = 1)
returns 1.0001
round_smart(1.0001234, signif_digits = 2)
returns 1.00012
The maximum number of digits (default: 6) to round to.
round_smart(1.0000001234, max_digits = 6)
returns 1
round_smart(1.0000001234, max_digits = Inf)
returns 1.0000001
library(BioMathR)
library(dplyr)
default_opts <- options()
options(digits = 10, scipen = 999)
before <- data.frame(
V1 = c(123456, 1234),
V2 = c(-123, -0.12345),
V3 = c(1.0012345, 0.1),
V4 = c(1.1, 0.0012345),
V5 = c(1.000000012345, 0),
V6 = c(NA, -5.0018),
V7 = c(NA_real_, NA_real_)
)
before
#> V1 V2 V3 V4 V5 V6 V7
#> 1 123456 -123.00000 1.0012345 1.1000000 1.000000012 NA NA
#> 2 1234 -0.12345 0.1000000 0.0012345 0.000000000 -5.0018 NA
mutate(before, across(everything(), ~round_smart(.)))
#> V1 V2 V3 V4 V5 V6 V7
#> 1 123456 -123.0 1.001 1.100 1 NA NA
#> 2 1234 -0.1 0.100 0.001 0 -5.002 NA
mutate(before, across(everything(), ~round_smart(., signif_digits = 3)))
#> V1 V2 V3 V4 V5 V6 V7
#> 1 123456 -123.000 1.00123 1.10000 1 NA NA
#> 2 1234 -0.123 0.10000 0.00123 0 -5.0018 NA
mutate(before, across(everything(), ~round_smart(., signif_digits = 3, max_digits = Inf)))
#> V1 V2 V3 V4 V5 V6 V7
#> 1 123456 -123.000 1.00123 1.10000 1.000000012 NA NA
#> 2 1234 -0.123 0.10000 0.00123 0.000000000 -5.0018 NA
options(default_opts)