Table of Contents
To check if an element of a large vector meets multiple conditions, you can use logical indexing by combining multiple comparisons using the logical operators & (and) and | (or). This will return a logical array with elements set to either true or false depending on whether the conditions are met. You can then use this logical array to index into the vector and extract the elements that meet the desired 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.
The following tutorials explain how to perform other common tasks in R: