biogeek
biogeek

Reputation: 197

How to check if elements in one vector are equal to another vector in R?

I have two unequal vectors

x <- c(5,5,5,5,5,5)
y <- c(5,5)

I want to check if all elements in x is equal to all elements in y.

I tried if(mean(x) - mean(y) == 0 & sd(x) - sd(y) ==0){count=count+1} However, I realized that some unique combination of elements can have same mean for x and y, and identical standard deviation. Any suggestions on how I can achieve this ?

Upvotes: 1

Views: 8022

Answers (1)

Rich Pauloo
Rich Pauloo

Reputation: 8392

Use a logical test on all unique values:

x <- c(5,5,5,5,5,5)
y <- c(5,5)
z <- c(3,5,5)

> ifelse(unique(x) == unique(y), TRUE, FALSE)
[1] TRUE

> ifelse(unique(x) == unique(z), TRUE, FALSE)
[1] FALSE  TRUE

If you want only one output, use all(), which returns TRUE if all values are TRUE:

> all(ifelse(unique(x) == unique(y), TRUE, FALSE))
[1] TRUE

> all(ifelse(unique(x) == unique(z), TRUE, FALSE))
[1] FALSE

Upvotes: 2

Related Questions