2

Having a dataframe like this

df <- data.frame(ID = sample(rep(letters, each=3)), value = rnorm(n=26*3))
keep <- c("a", "d", "r", "x")

How is it possible to keep both "a" and "d"

example using something like this: df[df$ID == "a"|"d", ]

Nathalie
  • 1,228
  • 7
  • 20

3 Answers3

2

Use %in%

df[df$ID %in% c("a","d"), ]
linog
  • 5,786
  • 3
  • 14
  • 28
1

We can use base R function which(). which() returns indexes where given condition is met.

df[which(df$ID == "a" | df$ID == "d"),]
BetterCallMe
  • 636
  • 7
  • 15
1

An option with %chin%

library(data.table)
setDT(df)[ID %chin% c('a', 'd')]
akrun
  • 874,273
  • 37
  • 540
  • 662