# r – Comparing two vectors in an if statement

## r – Comparing two vectors in an if statement

`all`

is one option:

```
> A <- c(A, B, C, D)
> B <- A
> C <- c(A, C, C, E)
> all(A==B)
[1] TRUE
> all(A==C)
[1] FALSE
```

But you may have to watch out for recycling:

```
> D <- c(A,B,A,B)
> E <- c(A,B)
> all(D==E)
[1] TRUE
> all(length(D)==length(E)) && all(D==E)
[1] FALSE
```

The documentation for `length`

says it currently only outputs an integer of length 1, but that it may change in the future, so thats why I wrapped the length test in `all`

.

Are they identical?

```
> identical(A,C)
[1] FALSE
```

Which elements disagree:

```
> which(A != C)
[1] 2 4
```

#### r – Comparing two vectors in an if statement

Id probably use `all.equal`

and `which`

to get the information you want. Its not recommended to use `all.equal`

in an `if...else`

block for some reason, so we wrap it in `isTRUE()`

. See `?all.equal`

for more:

```
foo <- function(A,B){
if (!isTRUE(all.equal(A,B))){
mismatches <- paste(which(A != B), collapse = ,)
stop(error the A and B does not match at the following columns: , mismatches )
} else {
message(Yahtzee!)
}
}
```

And in use:

```
> foo(A,A)
Yahtzee!
> foo(A,B)
Yahtzee!
> foo(A,C)
Error in foo(A, C) :
error the A and B does not match at the following columns: 2,4
```