# Tagging values unique to a group in a dataframe

**URL:** https://discourse.julialang.org/t/tagging-values-unique-to-a-group-in-a-dataframe/97967
**Category:** Data
**Created:** [April 26, 2023, 8:11pm UTC](https://discourse.julialang.org/t/tagging-values-unique-to-a-group-in-a-dataframe/97967 "2023-04-26T20:11:37Z")
**Posts on this page:** 3
**Page:** 1

<div class="post-metadata">

### Author: ![George9000](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/george9000/32/23619_2.png) [@George9000](https://discourse.julialang.org/u/George9000)
#### Post date: [April 26, 2023, 8:11pm UTC](https://discourse.julialang.org/t/tagging-values-unique-to-a-group-in-a-dataframe/97967/1 "2023-04-26T20:11:37Z")

</div>

Say that I have a dataframe:

```julia
function exampl()
    grp = Int8[]
    for i in 1:5
        grp = append!(grp, fill(i, 7))
    end

    values = Int8[]
    for i in 1:7
        values = append!(values, rand(1:15, 5))
    end

    df = DataFrame(grp = grp, values = values)
    gdf = groupby(df, :grp)
    combine(gdf, :values => unique)
end

```

```julia
julia> exampl()
25×2 DataFrame
 Row │ grp values_unique 
     │ Int8 Int8          
─────┼─────────────────────
   1 │ 1 11
   2 │ 1 3
   3 │ 1 9
   4 │ 1 6
   5 │ 1 1
   6 │ 1 15
   7 │ 2 8
   8 │ 2 2
   9 │ 2 10
  10 │ 2 11
  11 │ 2 3
  12 │ 3 5
  13 │ 3 15
  14 │ 3 1
  15 │ 3 4
  16 │ 3 14
  17 │ 4 12
  18 │ 4 15
  19 │ 4 10
  20 │ 4 4
  21 │ 4 14
  22 │ 5 3
  23 │ 5 8
  24 │ 5 1
  25 │ 5 4

```

How would I create a third column `unique_to_group`, a Boolean value that shows if the value in each row is unique to only that group compared with other groups. Example: row 3, with value 9 would be flagged as `true` in the new column as it is unique to grp 1 only. I have been trying `setdiff!` approaches but haven’t been able to make it work.

---

<div class="post-metadata">

### Author: ![bertschi](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/bertschi/32/33462_2.png) [@bertschi](https://discourse.julialang.org/u/bertschi)
#### Post date: [April 26, 2023, 8:27pm UTC](https://discourse.julialang.org/t/tagging-values-unique-to-a-group-in-a-dataframe/97967/2 "2023-04-26T20:27:30Z")

</div>

If I understand correctly, turning the problem around should work:

```julia
using Chain

df = exampl()

@chain df begin
    groupby(:values_unique)
    transform(:grp => (x -> length(unique(x)) == 1) => :ha)
end

```

---

<div class="post-metadata">

### Author: ![George9000](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/george9000/32/23619_2.png) [@George9000](https://discourse.julialang.org/u/George9000)
#### Post date: [April 27, 2023, 1:59am UTC](https://discourse.julialang.org/t/tagging-values-unique-to-a-group-in-a-dataframe/97967/3 "2023-04-27T01:59:12Z")

</div>

Yes! Indeed, turning the problem around. Thank you so much.
