How to Select Rows by Condition in R (With Examples)


You can use one of the following methods to select rows by condition in R:

Method 1: Select Rows Based on One Condition

df[df$var1 == 'value', ]

Method 2: Select Rows Based on Multiple Conditions

df[df$var1 == 'value1' & df$var2 > value2, ]

Method 3: Select Rows Based on Value in List

df[df$var1 %in% c('value1', 'value2', 'value3'), ]

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

#create data frame
df <- data.frame(points=c(1, 2, 4, 3, 4, 8),
                 assists=c(6, 6, 7, 8, 8, 9),
                 team=c('A', 'A', 'A', 'B', 'C', 'C'))

#view data frame
df

  points assists team
1      1       6    A
2      2       6    A
3      4       7    A
4      3       8    B
5      4       8    C
6      8       9    C

Method 1: Select Rows Based on One Condition

The following code shows how to select rows based on one condition in R:

#select rows where team is equal to 'A'
df[df$team == 'A', ]

  points assists team
1      1       6    A
2      2       6    A
3      4       7    A

Notice that only the rows where the team is equal to ‘A’ are selected.

We can also use != to select rows that are not equal to some value:

#select rows where team is not equal to 'A'
df[df$team != 'A', ]

  points assists team
4      3       8    B
5      4       8    C
6      8       9    C

Method 2: Select Rows Based on Multiple Conditions

The following code shows how to select rows based on multiple conditions in R:

#select rows where team is equal to 'A' and points is greater than 1
df[df$team == 'A' & df$points > 1, ]

  points assists team
2      2       6    A
3      4       7    A

Notice that only the rows where the team is equal to ‘A’ and where points is greater than 1 are selected.

Method 3: Select Rows Based on Value in List

The following code shows how to select rows where the value in a certain column belongs to a list of values:

#select rows where team is equal to 'A' or 'C'
df[df$team %in% c('A', 'C'), ]

Notice that only the rows where the team is equal to ‘A’ or ‘C’ are selected.

Additional Resources

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

How to Select Rows Where Value Appears in Any Column in R
How to Select Specific Columns in R
How to Select Columns by Index in R

Leave a Reply

Your email address will not be published.