Search code examples
rbuilt-in

Round close to 0 values


In Mathematica there exists a command called Chop that replaces approximate real numbers that are close to zero by the exact integer 0.

I guess that I can build my own function, something like

chop <- function(x, tol = 1e-16) {
    ifelse(abs(x) >= tol, x, 0)
}

But is there any built-in function in R already?

EDIT: I just want to round values close to 0. For instance:

x <- 1e-4
chop(x, tol = 1e-3)
#0
chop(1+x, tol = 1e-3)
#1.0001

Solution

  • zapsmall() does get you close, but this requires a vector with a rather large number in it to compare.

    zapsmall(3.5e-5, digits = 4)
    #3.5e05
    
    zapsmall(c(3.5e-5, 3.6e10), digits = 4)
    #0.0e+00 3.6e+10
    

    To display it properly you can wrap it around with format()

    format(zapsmall(as.numeric(c(3.5e-5, 3.6e10)), digits = 3), scientific = FALSE, trim = TRUE)
    # "0" "36000000000"