3

I have a dataset of, say, 150 countries from which I would like to select records of, for instance, 50 countries that I already have a vector of. How can I filter needed countries? It's troubling to repetitively use | like:

filter(mydata, country == "A" | country == "B")

Recommendation much appreciated.

rsl
  • 131
  • 1
  • 3

1 Answers1

2

You can use %in%.

An example data set:

mydata <- data.frame(country = LETTERS[1:10])
#    country
# 1        A
# 2        B
# 3        C
# 4        D
# 5        E
# 6        F
# 7        G
# 8        H
# 9        I
# 10       J

Vector of letters:

vec <- c("A", "B", "C")

The code:

library(dplyr)
filter(mydata, country %in% vec)
#   country
# 1       A
# 2       B
# 3       C
Sven Hohenstein
  • 80,497
  • 17
  • 145
  • 168