near R Function of dplyr Package (2 Examples)

 

In this article, I’ll illustrate how to compare numeric vectors with the near function of the dplyr package in R programming.

The post is structured as follows:

Let’s take a look at some R codes in action!

 

Creating Exemplifying Data

We’ll use the following example data for the examples of this R tutorial:

x1 <- 1:5                         # Create two numeric vectors
x2 <- c(1, 2.1, 2.9, 4.5, 5)

Furthermore, we need to install and load the dplyr package to R to be able to use the near function:

install.packages("dplyr")         # Install dplyr add-on package
library("dplyr")                  # Load dplyr add-on package

Now, we can move on to the examples. So keep on reading!

 

Example 1: Basic Application of near Function

Example 1 shows the basic application of the near R function. Have a look at the following R code:

near(x1, x2)                      # Apply near function
# TRUE FALSE FALSE FALSE  TRUE

As you can see, the near function returns a logical vector to the RStudio console.

Each element of this vector shows whether the two numeric elements at this position of our two vectors are the same.

In this example, the first and the fifth elements of our two input vectors are the same.

 

Example 2: Apply near Function with User-Defined Tolerance

A useful option of the near function is the tol argument. The tol argument allows for an increased tolerance for the comparison, i.e. values can be considered the same as long as their difference is below the tolerance threshold.

Let’s have a look at the tol argument in action:

near(x1, x2, tol = 0.2)           # near function with tolerance
# TRUE  TRUE  TRUE FALSE  TRUE

In the previous R syntax, we specified the tolerance to be equal to 0.2. For that reason, the second and third elements of our input vectors are also considered to be the same. You may increase or decrease the tolerance according to your specific needs.

 

Video, Further Resources & Summary

Do you need more information on the content and the functions of the dplyr package? Then you might have a look at the following video of my YouTube channel.

 

 

Furthermore, you may have a look at this tutorial, since it explains the usage of the == operator, which is very similar to the near function.

In addition, you may have a look at the related tutorials on this homepage:

 

At this point you should know how to compare two numeric vectors with the dplyr package in the R programming language. In case you have any additional questions, please let me know in the comments section.

 



Leave a Reply

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

Fill out this field
Fill out this field
Please enter a valid email address.

Menu
Top