R: How to Select Rows in Data Frame Based on Values in Vector


You can use one of the following methods to select rows from a data frame in R based on values in a vector:

Method 1: Use Base R

new_df <- df[df$column_name %in% values_vector, ]

Method 2: Use dplyr Package

library(dplyr)

new_df <- df %>% filter(column_name %in% values_vector)

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

#create data frame
df <- data.frame(division=c('West', 'West', 'East', 'East', 'North'),
                 points=c(120, 100, 104, 98, 105),
                 assists=c(30, 35, 64, 28, 23))

#view data frame
df

  division points assists
1     West    120      30
2     West    100      35
3     East    104      64
4     East     98      28
5    North    105      23

Example 1: Use Base R to Select Rows Based on Values in Vector

We can use the following code to select only the rows from the original data frame where the value in the division column is equal to ‘West’ or ‘North.’

#define values of interest
my_values <- c('West', 'North')

#select rows that contain 'West' or 'North' in division column
new_df <- df[df$division %in% my_values, ]

#view results
new_df

  division points assists
1     West    120      30
2     West    100      35
5    North    105      23

The new data frame only contains the rows where the value in the division column is equal to ‘West’ or ‘North.’

Example 2: Use dplyr to Select Rows Based on Values in Vector

We can also use the filter() function from the dplyr package in R select only the rows from the original data frame where the value in the division column is equal to ‘West’ or ‘North.’

library(dplyr)

#define values of interest
my_values <- c('West', 'North')

#select rows that contain 'West' or 'North' in division column
new_df <- df %>% filter(division %in% my_values)

#view results
new_df

  division points assists
1     West    120      30
2     West    100      35
3    North    105      23

The new data frame only contains the rows where the value in the division column is equal to ‘West’ or ‘North.’

Note: The base R and dplyr methods produce the same results. However, the dplyr method will tend to be faster when working with extremely large data frames.

Additional Resources

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

How to Select Random Rows in R Using dplyr
How to Select Rows by Condition in R
How to Select Rows Where Value Appears in Any Column in R

Leave a Reply

Your email address will not be published.