Extract elements common in more than one column group

Viewed 22

I have an R dataset as shown below

   Lake   Month.Day     Parameter
1   A     01-2003       chloride
2   A     01-2003       conductivity
3   B     02-2004       chloride
4   C     09-2007       conductivity
5   D     12-2008       chloride
6   D     12-2008       conductivity
7   D     02-2011       conductivity

I want my new data set to only show the lakes that have both chloride and conductivity data for the same date. In this case, the new data frame would show:

   Lake   Month.Day     Parameter
1   A     01-2003       chloride
2   A     01-2003       conductivity
5   D     12-2008       chloride
6   D     12-2008       conductivity

Is there a way to do this? Thanks in advance.

1 Answers

Here is a simple solution for you: We first group the data set by our desired variables, 'Lake' and 'Month.Day'. Then we make sure that both of the 'Parameter' values are present in the 'Parameter' variable in each group. So if both are present the all function returns TRUE and that group will be selected.

library(dplyr)

df %>%
  group_by(Lake, Month.Day) %>%
  filter(all(c("chloride", "conductivity") %in% Parameter))

# A tibble: 4 x 3
# Groups:   Lake, Month.Day [2]
  Lake  Month.Day Parameter   
  <chr> <chr>     <chr>       
1 A     01-2003   chloride    
2 A     01-2003   conductivity
3 D     12-2008   chloride    
4 D     12-2008   conductivity
Related