Mee
Mee

Reputation: 25

filter by values that appear in one or another column in R

I have this data frame:

intA <- c('A', 'A', 'A', 'D', 'D', 'F', 'L')
intB <- c('B', 'D', 'T', 'T', 'B', 'K', 'M')
num <- c(1:7)
num2 <- c(6,6,7,7,7,6,7)
df <- data.frame(intA, intB, num, num2)
df

and I want to filter the data frame when in column intA or intB appears value A or T, I know how to filter by one or another, but I need to filter boths at the same time:

library(dplyr)
p <- c('A', 'T')

filter(df, intA %in% p)
filter(df, intB %in% p)

the expect output would be: intA intB num num2 1 A B 1 6 2 A D 2 6 3 A T 3 7 2 D T 4 7

Thank you in advance!

Upvotes: 0

Views: 38

Answers (2)

AndreasM
AndreasM

Reputation: 942

You can combine both conditions with OR, i.e., the | operator.

filter(df, intA %in% p | intB %in% p)

  intA intB num num2
1    A    B   1    6
2    A    D   2    6
3    A    T   3    7
4    D    T   4    7

´´´

Upvotes: 1

Karthik S
Karthik S

Reputation: 11584

Does this work:

> library(dplyr)
> df %>% rowwise() %>% filter(grepl('[AT]', intA) | grepl('[AT]', intB))
# A tibble: 4 x 4
# Rowwise: 
  intA  intB    num  num2
  <chr> <chr> <int> <dbl>
1 A     B         1     6
2 A     D         2     6
3 A     T         3     7
4 D     T         4     7
> 

Upvotes: 0

Related Questions