Compare numeric vectors in R

Compare numeric vectors in R, we explore the usage of the ‘near’ function from the ‘dplyr’ package in R programming.

The article is divided into two examples, with the first one demonstrating the basic application of the ‘near’ function and the second one showcasing its flexibility with user-defined tolerance.

Compare numeric vectors in R

To begin, we create exemplifying data by defining two numeric vectors, ‘x1’ and ‘x2’.

x1 <- 1:5                         
x2 <- c(1, 2.2, 2.5, 4, 5.3)

We then install and load the ‘dplyr’ package to access the ‘near’ function.

Time Series Trend Analysis in R »

library(dplyr)

Example 1: we apply the ‘near’ function to our vectors

The function returns a logical vector, indicating whether the corresponding elements from both vectors are the same.

In this case, the first and fourth elements are identical.

near(x1, x2)    
[1] TRUE FALSE FALSE TRUE FALSE

Example 2: Baisis User-Defined Tolerance

In Example 2, we introduce the ‘tol’ argument, which allows for increased tolerance in the comparison.

near(x1, x2, tol = 0.2)   
[1] TRUE FALSE FALSE TRUE FALSE

By setting the tolerance to 0.2, the second and third elements of the input vectors are now considered the same.

Adjusting the tolerance can be beneficial depending on specific requirements.

Summary

The ‘near’ function from the ‘dplyr’ package in R is a valuable tool for comparing numeric vectors and offers flexibility through the ‘tol’ argument.

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *

four + 4 =