Search code examples
rdataframedplyrtidyversefiltering

summarise ids with the same row values data frame r


In my DATA below, I wonder how to list the unique IDs whose ALL Type rows ONLY consist of A to achieve my Desired_output?

I tried the following without success:

library(tidyverse)
group_by(DATA, ID) %>%
     filter(
        all("A" %in% Type))
DATA <- read.table(h=T,text=
"
ID      Type
1        A
1        A
1        A
2        B
2        B
2        A
3        A
3        A")

Desired_output =
"
ID       Type
1        A
1        A
1        A
3        A
3        A
"

Solution

  • You want == here, not %in%

    group_by(DATA, ID) %>%
      filter(
        all(Type == "A"))
    #      ID Type 
    #   <int> <chr>
    # 1     1 A    
    # 2     1 A    
    # 3     1 A    
    # 4     3 A    
    # 5     3 A