Filter out IDs with different values in a certain column

Hi,

I would like to filter out ID's which do not share the same 'place' value. So that in provided example I get just IDs A & C. I'll aprreacite your help.

library(dplyr)
#> 
#> Attaching package: 'dplyr'
#> The following objects are masked from 'package:stats':
#> 
#>     filter, lag
#> The following objects are masked from 'package:base':
#> 
#>     intersect, setdiff, setequal, union

data <- tibble(ID = c("A", "A", "B", "B", "C"),
               place = c("London", "London", "Berlin", "Prague", "Madrid"))

Many thanks,

Jakub

Here is one way to do it.

library(tidyverse)

data <- tibble(ID = c("A", "A", "B", "B", "C"),
               place = c("London", "London", "Berlin", "Prague", "Madrid"))

data |>
  distinct() |>
  group_by(ID) |>
  filter(n() == 1) |>
  ungroup()
#> # A tibble: 2 × 2
#>   ID    place 
#>   <chr> <chr> 
#> 1 A     London
#> 2 C     Madrid

Created on 2022-11-23 with reprex v2.0.2.9000

1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.