1

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 ?

biogeek
  • 197
  • 3
  • 8
  • 1
    do you just want `identical(x, y)` or `all.equal(x, y)` ? – SymbolixAU Sep 07 '17 at 01:03
  • can I please know what the difference is? – biogeek Sep 07 '17 at 01:06
  • see [this question](https://stackoverflow.com/q/3395696/5977215) – SymbolixAU Sep 07 '17 at 01:06
  • 2
    What about `length(setdiff(x, y)) == 0` this will work for non equal length and multiple distinct elements? – mt1022 Sep 07 '17 at 01:08
  • 3
    Can you include a complete example? For this `all(unique(x) %in% unique(y))` seem to work. – Ronak Shah Sep 07 '17 at 01:11
  • 1
    @RonakShah, that code works for this example, but not when vectors have dissimilarity. For that, you need a logical test. – Rich Pauloo Sep 07 '17 at 01:25
  • 3
    `identical(sort(unique(x)), sort(unique(y)))` – d.b Sep 07 '17 at 01:47
  • This seems to do the job. It would be helpful if you could explain what sort is doing here – biogeek Sep 07 '17 at 02:36
  • @biogeek, try running `?sort()` in your R console. It a function in base R. The documentation you can find when enter `?sort()` says: **"Sort (or order) a vector or factor (partially) into ascending or descending order."** It's basically sorting all unique values of x and y into a vector. Then with `identical()`, we ask if those vectors are exactly the same. If they are, then it stands to reason that all of the values in x are also in y. – Rich Pauloo Sep 07 '17 at 03:14

1 Answers1

1

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
Rich Pauloo
  • 7,734
  • 4
  • 37
  • 69
  • I'm trying to use `count = count +1` and so I tried to do `if(unique(x) == unique(y)){count=count+1}` followed but another else condition that is part of my larger code. But I keep running into an error that says `the condition has length > 1 and only the first element will be used` – biogeek Sep 07 '17 at 02:31
  • `count` in the dplyr package? I'm not exactly sure what you're asking, but to the problem you posed, the solutions above work, as does @d.b.'s solution: `identical(sort(unique(x)), sort(unique(y)))` – Rich Pauloo Sep 07 '17 at 03:09