Subsetting with multiple conditions in R, The filter() method in the dplyr package can be used to filter with many conditions in R.
With an example, let’s look at how to apply a filter with several conditions in R.
Let’s start by making the data frame.
df<-data.frame(Code = c('A','B', 'C','D','E','F','G'), Score1=c(44,46,62,69,85,77,68), score2=c(35,78,45,89,67,49,70), score3=c(57,62,55,88,43,90,57)) df
As a result, the final data frame will be
Code score1 score2 score3 1 A 44 35 57 2 B 46 78 62 3 C 62 45 55 4 D 69 89 88 5 E 85 67 43 6 F 77 49 90 7 G 68 70 57
Online Course R Statistics: Statistics with R »
Subsetting with multiple conditions in R
Using the or condition to filter two columns.
Let’s load dpyr package first,
library(dplyr) result <- df%>% filter(score>50 | score2>55) result
as a result, the filtered data frame
Code score1 score2 Score3 1 B 46 78 62 2 C 62 45 55 3 D 69 89 88 4 E 85 67 43 5 F 77 49 90 6 G 68 70 57
Filtering with multiple conditions in R:
Using and condition to filter two columns.
library(dplyr) df2 <- df %>% filter(score1>45 & score2>45) df2
so the filtered data frame is
Code score1 score2 Score3 1 B 46 78 62 2 D 69 89 88 3 E 85 67 43 4 F 77 49 90 5 G 68 70 57