# Adding columns based on unique values

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

If you work with relatively complex data frames, there are tools for such things in packages like Query. 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:

``````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
``````

Great work. Thank you a lot