Home > OS >  Filter multiple values in 2 different columns for specified conditions
Filter multiple values in 2 different columns for specified conditions

Time:10-24

Sample data:

df <- data.frame(
  dr=c('john', 'jill', 'jill', 'john'),
  service=c('PT','SN','SN','PT'),
  Hours=c(6,5,4,8)
)

I tried filtering it to get the output as below with values to be displayed greater than 4 for SN and greater than 6 for PT.

Output should be

Dr.   Service.   Hours
Jill.   SN.        5
John.   PT.        8

I have 2000 rows of such filtering and unsure how to go about.

CodePudding user response:

You can specify the conditions as follows:

library(dplyr)

df <- data.frame(
  dr=c('john', 'jill', 'jill', 'john'),
  service=c('PT','SN','SN','PT'),
  Hours=c(6,5,4,8)
)

df %>% 
  filter(
    (service == 'SN' & Hours > 4) |
      (service == 'PT' & Hours > 6)
  )

CodePudding user response:

In base R you can try using subset:

subset(
  df,
  service == "SN" & Hours > 4 | service == "PT" & Hours > 6
)

or place the evaluation in brackets to extract rows that meet the conditions:

df[(df$service == "SN" & df$Hours > 4) | (df$service == "PT" & df$Hours > 6),]

Output

    dr service Hours
2 jill      SN     5
4 john      PT     8
  • Related