Table of Contents
To select rows in a data frame based on values in a vector, you can use the subset function to filter out the rows that contain the values specified in the vector. This can be done by specifying the data frame and the vector within the subset function. The syntax for this will look like subset(data frame, vector). This will return a subsetted data frame with only the rows that contain the values specified in the 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 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.