Take "a" and "b" as equal if they are the same in their first 4 decimal places in R

I was wondering, how could I use R for any two objects, such as " a" and " b" ( shown below ) as equal if they are EXACTLY the same in the first 4 decimal places ?

PS Thus, I ask how I can make a conditional command from this question.

a = 1.234574789

b = 1.234565638
+4
source share
3 answers

If you want to see how to code a custom function:

> equal <- function(a, b, sig=4) { return (round(a,sig) == round(b,sig)) }
> equal(1.23456, 1.23457)
[1] TRUE
> equal(1.23456, 1.23557)
[1] FALSE
+2
source

We can check the first 6 places, with substr

substr(a, 1, 6)== substr(b, 1, 6)

Or using sprintf

sprintf("%0.4f", a) == sprintf("%0.4f", b)
#[1] TRUE

f1 <- function(v1, v2) {
        sprintf("%0.4f", v1) == sprintf("%0.4f", v2)
 }

f1(a, b)
#[1] TRUE

f1(1.2345, 1.2346)
#[1] FALSE

round, round

round(a, 4)
#[1] 1.2346
round(b, 4)
#[1] 1.2346

,

+5

If you want to check whether aand are balmost equal within a certain tolerance, you can useall.equal

a = 1.234574789
b = 1.234565638
a - b
#[1] 9.151e-06

all.equal(a, b, tolerance = 1e-4)
#[1] TRUE

all.equal(a, b, tolerance = 1e-5)
#[1] TRUE

all.equal(a, b, tolerance = 1e-6)
#[1] "Mean relative difference: 7.41226865e-06"
+3
source

Source: https://habr.com/ru/post/1675541/


All Articles