filter a dataframe rows based on multiple values from a specific column in r

To filter rows in a dataframe based on multiple values from a specific column, you can use the %in% operator in combination with the filter() function from the dplyr package in R.

Here's an example code snippet:

main.r
library(dplyr)

# create sample dataframe
df <- data.frame(
  group = rep(letters[1:3], each = 3),
  value = 1:9
)

# filter rows based on multiple values in 'group' column
selected_groups <- c("a", "c")
filtered_df <- df %>% 
  filter(group %in% selected_groups)

# output filtered dataframe
print(filtered_df)
312 chars
16 lines

In this example, we first create a sample dataframe df with two columns: group and value. Then, we define the selected_groups vector to contain the values we want to filter the dataframe by (in this case, "a" and "c"). Next, we use the filter() function with the %in% operator to select rows where the value in the group column matches any of the values in selected_groups. Finally, we store the filtered dataframe in a new object called filtered_df and print it to the console.

This will output:

main.r
  group value
1     a     1
2     a     2
3     a     3
4     c     7
5     c     8
6     c     9
98 chars
8 lines

gistlibby LogSnag