Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between two vectors in R

Tags:

r

diff

vector

I have two vectors:

a <- c(1, 1, 3, 4, 5, 7, 9)
b <- c(2, 3, 4, 6, 8, 2)

I want to find the numbers in the second vector, which are not in the first vector:

dif <- c(2, 6, 8)

I've tried many different approaches (such as merge, different types of joins (dplyr package), setdiff, compare (compare package)), but I still can't find a way to do it.

like image 922
Jot eN Avatar asked Jul 22 '15 20:07

Jot eN


People also ask

How do you find the difference between two vectors in R?

Method 1: Using setdiff() method The setdiff() method in R is used to retrieve the elements of vector X, which are not contained in Y. This method can be applied where the two vectors may belong to different data types, as well, where the elements of the first argument vector are returned unmodified.

What is the difference between and [[ ]] in R?

Hey Latha, The difference between them is that [[ ]] is used to access a component in a list or matrix whereas [ ] is used to access a single element in a matrix or array.


2 Answers

You can use setdiff

setdiff(b,a)
#[1] 2 6 8
like image 126
akrun Avatar answered Oct 19 '22 01:10

akrun


An alternative way, instead of setdiff (which is probably preferrable), is to use %in%

unique(b[! b %in% a])
#[1] 2 6 8
like image 18
nico Avatar answered Oct 19 '22 02:10

nico