Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find a value/values of a data frame that belongs to only one group in R [duplicate]

Tags:

r

dplyr

I have a sample data frame

s1=data.frame(no=c(1,2,3,4,5,6,7),car_mod=c("car1","car2","car2","car3","car2","car1","car4"),col=c("red","black","red","blue","black","blue","red"))
  no car_mod   col
1  1    car1   red
2  2    car2 black
3  3    car2   red
4  4    car3  blue
5  5    car2 black
6  6    car1  blue
7  7    car4   red

I need to find which value of the column "col" is present only in one group of the column "car_mod"

For example "black" is present only in rows that have the value car2 under "car_mod" I need a list of all of those values and the rows

The output should look something like this

black
      no car_mod   col
    1  2    car2 black
    2  5    car2 black

Thank you! (the actual dataframe is much larger)

like image 681
lolbye Avatar asked Sep 03 '25 02:09

lolbye


1 Answers

Here is a way using group_by:

  library(dplyr)
  s1 |> 
    group_by(col) |> 
    filter(n_distinct(car_mod) == 1) |> 
    ungroup()
# A tibble: 2 × 3
     no car_mod col  
  <dbl> <chr>   <chr>
1     2 car2    black
2     5 car2    black
like image 194
Julian Avatar answered Sep 07 '25 06:09

Julian