Search code examples
rdataframeconditional-statementsdata-manipulation

If values in two columns satisfy two different conditions, store corresponding value of third column into a list in R


I have a data frame that looks like this:

col1   col2    col3    y
1      2       2       10
0      1       0       15
2      2       1       17
1      2       1       9
2      0       0       8
0      1       2       21

I want to store the value in y in a list if col1 and col2 meet two separate conditions.

In this example my conditions are if if the value in col1 == 0 and the value in col2 == 1, then store the value of y in the list.

col3 is completely ignored. I just added it in here because my actual dataframe has many columns that I am not interested in.

So, in this example, the result would be a list of length 2 with the values "15" and "21" inside.


Solution

  • library(dplyr)
    
    
    data <-
      data.frame(
        col1 = c(1,0,2,0),
        col2 = c(2,1,2,1),
        y = c(10,15,17,21)
      )
    
    data %>% 
      filter(col1 == 0 & col2 == 1) %>% 
      pull(y) %>% 
      as.list()