R: How to Filter Rows where Column is Between Two Values


You can use the following methods to filter a data frame in R where a specific column is between wo values:

Method 1: Use Base R

df_new <- subset(df, points %in% 100:120)

Method 2: Use dplyr

library(dplyr)

df_new <- df %>% filter(between(points, 100, 120))

Both of these examples filter a data frame to only contain the rows where the value in the points column is between 100 and 120.

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

#create data frame
df <- data.frame(team=c('Mavs', 'Pacers', 'Mavs', 'Celtics', 'Nets', 'Pacers'),
                 points=c(104, 110, 134, 125, 114, 124),
                 assists=c(22, 30, 35, 35, 20, 27))

#view data frame
df

     team points assists
1    Mavs    104      22
2  Pacers    110      30
3    Mavs    134      35
4 Celtics    125      35
5    Nets    114      20
6  Pacers    124      27

Example 1: Filter where Column is Between Two Values Using Base R

We can use the following syntax with the subset() function from base R to filter the data frame to only contain rows where the value in the points column is between 100 and 120:

#filter for rows where value in points column is between 100 and 120
df_new <- subset(df, points %in% 100:120) 

#view updated data frame
df_new

    team points assists
1   Mavs    104      22
2 Pacers    110      30
3   Nets    114      20

Notice that only the rows where the value in the points column is between 100 and 120 are kept.

All other rows with a value outside of this range are dropped.

Example 2: Filter where Column is Between Two Values Using dplyr

We can use the following syntax with the filter() and between() functions from the dplyr package in R to filter the data frame to only contain rows where the value in the points column is between 100 and 120:

library(dplyr)

#filter for rows where value in points column is between 100 and 120
df_new <- df %>% filter(between(points, 100, 120))

#view updated data frame
df_new

    team points assists
1   Mavs    104      22
2 Pacers    110      30
3   Nets    114      20

Notice that only the rows where the value in the points column is between 100 and 120 are kept.

Also notice that this method produces the same output as the base R method.

Note: You can find the complete documentation for the filter function in dplyr here.

Additional Resources

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

How to Use %in% to Filter for Rows with Value in List in R
How to Filter by Multiple Conditions Using dplyr
How to Filter Rows that Contain a Certain String Using dplyr

Leave a Reply

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