Error: Reducing over an empty collection is not allowed

Hi everyone,

I am trying to sort and sum data based off of the first column of ‘DNVGL_total’ into a new array. However, when trying to do this, I get the error ‘Reducing over an empty collection is not allowed’

I am new and any help would be appreciated

It’s significantly easier to help if you post code as text instead of screenshots. You can pass the init=0 keyword to the sum function to provide it with a default value in the empty case:

sum(blah blah; init=0)

Note that the semicolon is necessary when the argument is a generator expression to help the parser know that you’re passing a keyword argument, not iterating over something new.

11 Likes

DNVGL_total =
[
2 1568 19 6 42 0 0 0
4 938 47 2 45 0 0 0
1 621 55 6 8 0 0 0
5 571 49 5 29 21 0 0
5 220 32 18 0 0 0 0
3 195 13 16 8 0 0 0
1 115 7 0 0 2 34 0
3 103 15 3 0 0 0 0
3 93 22 3 12 1 0 0
3 60 10 0 0 0 0 0
5 12 53 194 4 0 0 2
5 6 20 89 1 0 0 0
5 1 3 18 0 0 0 0
5 1 0 13 0 0 0 0
5 0 37 59 0 0 0 0
5 0 18 16 0 0 0 1
]
(Y,Z) = size(DNVGL_total)

DNVGL_total_sort = zeros(5,7)
for t=1:5
for a=1:7
DNVGL_total_sort[t,a] = sum(DNVGL_total[i,a+1] for i=1:Y if DNVGL_total[1:Y,1] == t)
end
end

#I want to create a new table that sums over the rows for each column, if the value in column 1 of DNVGL_total is equal to the row number of the new table

You can use triple backticks ``` to write code.

What about:

julia> [a == 1 ? t : sum(DNVGL_total[findall(DNVGL_total[:,1].==t),a]) for t in 1:5, a in 1:8]
5×8 Array{Int64,2}:
 1   736   62    6   8   2  34  0
 2  1568   19    6  42   0   0  0
 3   451   60   22  20   1   0  0
 4   938   47    2  45   0   0  0
 5   811  212  412  34  21   0  3

(The first element of the row is unchanged.)

1 Like

yes, thank you that is perfect!

I am using Julia 1.5.2 and this did not work: sum([];init=0) is giving me ERROR: MethodError: no method matching sum(::Array{Any,1}; init=0) but reduce(+, []; init=0) is working fine. Same thing with an iterator instead of an empty array.

1 Like

The init keyword to sum was added in 1.6, which isn’t released yet.

5 Likes

Is there an alternative to “init” before version 1.6?