user2543622
user2543622

Reputation: 6766

R vector find common elements and remove elements that are not common

I want to find elements that are common to two vectors. I can use intersect(a,b) to do the same.

But then i want to remove elements of a and b that are not common and reduce a and b to smaller sizes without changing order of elements

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

I want new a and b to be

a will be (3,9) and b will be (9,3)

Upvotes: 0

Views: 2250

Answers (2)

Gustavo B Paterno
Gustavo B Paterno

Reputation: 986

Following the suggestion made by Frank.

The simplest way is to use intersect

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

# Use `intersect` on both ways: 
a <- intersect(a,b)
b <- intersect(b,a)

# Desired results:
a
[1] 3 9
b
[1] 9 3

Cheers

Upvotes: 4

mpalanco
mpalanco

Reputation: 13570

a <- a[a%in%b]
[1] 3 9
b <- b[b%in%a] 
[1] 9 3

Upvotes: 2

Related Questions