# How to Compare Two Vector Objects in R (5 Examples)

This tutorial illustrates how to compare vectors in the R programming language.

## Creating Example Data

x <- c("A", "B", "C") # Constructing two example vectors y <- c("A", "B", "D") |

x <- c("A", "B", "C") # Constructing two example vectors y <- c("A", "B", "D")

## Example 1: Are Both Vectors Identical?

identical(x, y) # Test whether vectors are identical # [1] FALSE |

identical(x, y) # Test whether vectors are identical # [1] FALSE

## Example 2: Which Vector Elements are the Same?

x == y # Test for equal elements # [1] TRUE TRUE FALSE |

x == y # Test for equal elements # [1] TRUE TRUE FALSE

## Example 3: Which Elements of First Vector Exit in Second?

x %in% y # Test for existence of elements # [1] TRUE TRUE FALSE |

x %in% y # Test for existence of elements # [1] TRUE TRUE FALSE

## Example 4: Which Elements Exist in First & Second Vector?

intersect(x, y) # Test for elements that exist in both # [1] "A" "B" |

intersect(x, y) # Test for elements that exist in both # [1] "A" "B"

## Example 5: Which Elements Exist Only in First Vector?

setdiff(x, y) # Test for elements that exist only in first # [1] "C" |

setdiff(x, y) # Test for elements that exist only in first # [1] "C"