filter a dataframe based on two values from a column in r

To filter a dataframe based on two values from a specific column in R, you can use the %in% operator in combination with the subset function.

Assuming you have a dataframe df and you want to filter the rows where the values in column x are either "value1" or "value2", you can use the following code:

main.r
filtered_df <- subset(df, x %in% c("value1", "value2"))
56 chars
2 lines

This will create a new dataframe filtered_df that contains only the rows where the values in column x are either "value1" or "value2".

Alternatively, you can also use the dplyr package to filter a dataframe based on two values from a specific column. Assuming you have a dataframe df and you want to filter the rows where the values in column x are either "value1" or "value2", you can use the following code:

main.r
library(dplyr)

filtered_df <- df %>%
  filter(x %in% c("value1", "value2"))
77 chars
5 lines

This will create a new dataframe filtered_df that contains only the rows where the values in column x are either "value1" or "value2", using the piping operator %>% and the filter function from the dplyr package.

gistlibby LogSnag