Using the %in% operator

One additional, often used special operator is the %in% operator. It checks whether or not the contents of one vector are present in another one as well.

In the following example we use the variable EU containing the abbreviation of all countries in the European Union. Then, we check whether or not the character "AU" is present in the EU variable.

Input
EU <- c("AU","BE","BG","CY","CZ","DE","DK","EE","ES","FI","FR","GR","HR","HU",
        "IE","IT","LT","LU","LV","MT","NL","PO","PT","RO","SE","SI","SK")
"AU" %in% EU
Output
[1] TRUE

The following example extends the search and compares multiple elements with the contents of the EU variable. It outputs a logical vector as a result containing a logical value for each element:

Input
c("AU","HU","UK") %in% EU
Output
[1]  TRUE  TRUE FALSE

As the output shows, the first two character elements "AU" and "HU" are present in the variable EU, however the third element "UK" is not.

Use basic operators