sathya
sathya

Reputation: 177

compare two variables of different length using R

I need to compare the values stored in two variables.The variable sizes are different. For example

x = c(1,2,3,4,5,6,7,8,9,10)

and

y = c(2,6,11,12,13)

I need an answer that 2 and 6 are present in both variables. I need this to be done in R.Anyone help please.

Upvotes: 0

Views: 2501

Answers (3)

IRTFM
IRTFM

Reputation: 263332

Posted after the added requirement that some sort of tolerance be allowed: You could sequentially check one set of values against all the others in the second set or you could do it all at once with outer(). Once you have the outer result as a logical matrix there remains the task of referring back to the values, but expand.grid seems capable of handling that:

expand.grid(x,y)[outer(x,y, FUN=function(x,y) abs(x-y) < 0.01), ]
#   Var1 Var2
#2     2    2
#16    6    6

After posting It occurred to me that you values were sorted. Turns out that this extraction from expand.grid() survives passing unsorted vectors.

Upvotes: 2

Spacedman
Spacedman

Reputation: 94182

The intersect function avoids the need for @mdsumner's simple indexing:

> x = c(1,2,3,4,5,6,7,8,9,10)
> y = c(2,6,11,12,13)
> intersect(x,y)
[1] 2 6

Whole bunch of set operators to be found here: help(intersect)

Upvotes: 8

mdsumner
mdsumner

Reputation: 29477

x[x %in% y]
[1] 2 6

Or, more explicitly:

x[match(x, y, nomatch = 0) > 0]
[1] 2 6

Note that you actually chain together the results of the match with simple indexing into the input values.

See ?match.

Upvotes: 1

Related Questions