# Adding columns based on unique values

**URL:** <https://discourse.julialang.org/t/adding-columns-based-on-unique-values/37835>\
**Category:** General Usage\
**Created:** [April 19, 2020, 7:58am UTC](https://discourse.julialang.org/t/adding-columns-based-on-unique-values/37835 "2020-04-19T07:58:08Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![hmemy](https://avatars.discourse-cdn.com/v4/letter/h/50afbb/32.png) [@hmemy](https://discourse.julialang.org/u/hmemy)\
**Post date:** [April 19, 2020, 7:58am UTC](https://discourse.julialang.org/t/adding-columns-based-on-unique-values/37835/1 "2020-04-19T07:58:08Z")

</div>

Hi,

I have a table A and would like to obtain the unique values in the first column and add the corresponding values in the 2nd and 3rd columns. I have already implemented it in matlab using this line:  
res = [unique(A(:,1)), splitapply(@(x) sum(x,1), A(:,2:end), A(:,1))];

A = [  
1 0 0  
2 0 0  
3 0 0  
1 3 5  
1 2 9  
3 4 0 ]

The result must be:  
res = [  
1 5 14  
2 0 0  
3 4 0]

How can I achieve this in Julia?

Thank you

---

<div class="post-metadata">

**Author:** ![heliosdrm](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/heliosdrm/32/3851_2.png) [@heliosdrm](https://discourse.julialang.org/u/heliosdrm)\
**Post date:** [April 19, 2020, 9:44am UTC](https://discourse.julialang.org/t/adding-columns-based-on-unique-values/37835/2 "2020-04-19T09:44:11Z")

</div>

If you work with relatively complex data frames, there are tools for such things in packages like [Query](https://www.queryverse.org/Query.jl/stable/). But you can also use plain operations from base Julia.

In Matlab you are encouraged to use things like `splitapply` etc. to vectorize such operations, but in Julia you have not to be afraid of using `for` loops, if they are the natural choice for what you want to do.

You could do, for instance:

```julia
inds = unique(A[:,1])
n, m = size(A)
res = zeros(eltype(A), length(inds), m) 
res[:,1] .= inds # first column of `res` is the list of unique values
for i = 1:n
    # look for the row in `res` where you want to add the value
    row = findfirst(j -> j == A[i,1], inds)
    for col = 2:m
        res[row, col] += A[i,col]
    end
end
res

```

---

<div class="post-metadata">

**Author:** ![hmemy](https://avatars.discourse-cdn.com/v4/letter/h/50afbb/32.png) [@hmemy](https://discourse.julialang.org/u/hmemy)\
**Post date:** [April 19, 2020, 10:00am UTC](https://discourse.julialang.org/t/adding-columns-based-on-unique-values/37835/3 "2020-04-19T10:00:11Z")

</div>

Great work. Thank you a lot
