1

I am trying to find in a table a row which matches two column values. I know that I can use which function:

my_data[which(my_data$col1 == "val"),]

But how do I do this for 2 or more values? I've already tried && operator in any order, still doesn't help.

Igor Konoplyanko
  • 8,546
  • 6
  • 50
  • 91

3 Answers3

5

Using the filter function in dplyr you can do this without too much trouble. Try something like this:

my_data %>%
  filter(col1 == "val", col2 == "other")

By default, you have two or more statements, filter treats it as an AND, but you can be more explicit & like so

my_data %>%
  filter(col1 == "val" & col2 == "other")
beigel
  • 1,130
  • 8
  • 13
3

my_data[which(my_data$col1 == "val" & my_data$col2 == "val2"),] ought to work in base R.

lebelinoz
  • 4,380
  • 9
  • 27
  • 52
  • 1
    this actually works. It's strange, but it was not working because I had one column named with my_data$T , somehow "T" is glitching – Igor Konoplyanko Sep 28 '17 at 19:57
2

You can use subset in base R:

subset(my_data, col1 == "val" & col2 == "char")
M--
  • 18,939
  • 7
  • 44
  • 76