'Is there an R function to pick only certain row value combinations?

I have a data frame that looks something like this:

my_data <- data.frame( 
   letter = c("x","x","x","x","x","y","y","y","y","z","z","z","z"),
   number = c(1,5,6,7,2,3,4,5,6,1,4,4,4))

I now wish to make a new data_frame where only a certain picked combination of the columns exists ("x" can be 1,2 "y" can be 3 and "z" can be 4), so it will give something like this:

my_data2 <- data.frame( 
   letter = c("x","x","y","z","z"),
   number = c(1,2,3,4,4))

I can do this by if-else, but is there a more elegant way to do it?



Solution 1:[1]

my_data <- data.frame( 
  letter = c("x","x","x","x","x","y","y","y","y","z","z","z","z"),
  number = c(1,5,6,7,2,3,4,5,6,1,4,4,4))

library(tidyverse)
my_data %>% filter(letter == "x" & number %in% c(1,2) | 
                   letter == "y" & number == 3 |
                   letter == "z" & number == 4
                   )

  letter number
1      x      1
2      x      2
3      y      3
4      z      4
5      z      4
6      z      4


How to use or/and in dplyr to subset a data.frame

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1