R: How to Use which() Function with Multiple Conditions


You can use the following methods to use the which() function with multiple conditions in R:

Method 1: which() with Multiple Conditions Using AND

new_df <- df[which(df$my_column >= 14 & df$my_column <= 25), ]

Method 2: which() with Multiple Conditions Using OR

new_df <- df[which(df$my_column < 14 | df$my_column > 25), ] 

The following examples show how to use each method in practice with the following data frame:

#create data frame
df <- data.frame(player=c('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J'),
                 points=c(10, 13, 13, 15, 19, 22, 24, 25, 29, 35))

#view data frame
df

   player points
1       A     10
2       B     13
3       C     13
4       D     15
5       E     19
6       F     22
7       G     24
8       H     25
9       I     29
10      J     35

Example 1: which() with Multiple Conditions Using AND

The following code shows how to use the which() function to filter the data frame to only contain rows where the value in the points column is greater than or equal to 14 and less than or equal to 25:

#filter for players who score between 14 and 25 points
new_df <- df[which(df$points >= 14 & df$points <= 25), ]

#view results
new_df

  player points
4      D     15
5      E     19
6      F     22
7      G     24
8      H     25

Notice that the data frame is filtered to only contain rows where the value in the points column is greater than or equal to 14 and less than or equal to 25.

Note that the & operator is used as an “and” statement in R.

Example 2: which() with Multiple Conditions Using OR

The following code shows how to use the which() function to filter the data frame to only contain rows where the value in the points column is less than 14 or greater than 25:

Otherwise it assigns a value of “bad”:

#filter for players who score less than 14 or greater than 25 points
new_df <- df[which(df$points < 14 | df$points > 25), ]

#view results
new_df

   player points
1       A     10
2       B     13
3       C     13
9       I     29
10      J     35

Notice that the data frame is filtered to only contain rows where the value in the points column is less than 14 or greater than 25.

Note that the | operator is used as an “or” statement in R.

Additional Resources

The following tutorials explain how to perform other common tasks in R:

How to Use If Statement with Multiple Conditions in R
How to Write a Nested If Else Statement in R
How to Write a Nested For Loop in R

Leave a Reply

Your email address will not be published. Required fields are marked *