Forum Discussion
Sum array by group (quaters, years other) requires extra argument.
- Dec 29, 2023
Gary1234 While I can't provide a complete explanation, it seems that BYROW behaves differently when used on an array than it does with a range. Specifically, it appears the issue is caused by passing the entire row parameter i to each subsequent calculation, even though the array only contains a single column. The solution in this case is to define the iMax variable first as INDEX(i, 1), then use iMax instead of i for the remaining calculations:
=LAMBDA(Amount,Date,Count, LET( Seq, SEQUENCE(ROWS(Amount)), BYROW(Seq, LAMBDA(i, LET(iMax, INDEX(i, 1), iMin, IF((iMax - Count + 1) > 0, iMax - Count + 1, 1), SUM(INDEX(Amount, SEQUENCE(iMax - iMin + 1, 1, iMin)))))) ) )(C5:C28, B5#, E2)The function, as presented, could also be rewritten and simplified as follows:
=LAMBDA(Amount,Count, BYROW(SEQUENCE(ROWS(Amount)), LAMBDA(r, LET( n, INDEX(r, 1), m, MAX(n-Count+1, 1), SUM(INDEX(Amount, SEQUENCE(n-m+1,, m)))))))(C5:C28, E2)Having said that, the function does not actually sum the data by group. Rather, it's summing the previous n rows in the range. If this is the expected result, great. If not, then another approach is needed. Cheers!
Gary1234 While I can't provide a complete explanation, it seems that BYROW behaves differently when used on an array than it does with a range. Specifically, it appears the issue is caused by passing the entire row parameter i to each subsequent calculation, even though the array only contains a single column. The solution in this case is to define the iMax variable first as INDEX(i, 1), then use iMax instead of i for the remaining calculations:
=LAMBDA(Amount,Date,Count,
LET(
Seq, SEQUENCE(ROWS(Amount)),
BYROW(Seq, LAMBDA(i, LET(iMax, INDEX(i, 1), iMin, IF((iMax - Count + 1) > 0, iMax - Count + 1, 1), SUM(INDEX(Amount, SEQUENCE(iMax - iMin + 1, 1, iMin))))))
)
)(C5:C28, B5#, E2)
The function, as presented, could also be rewritten and simplified as follows:
=LAMBDA(Amount,Count,
BYROW(SEQUENCE(ROWS(Amount)), LAMBDA(r, LET(
n, INDEX(r, 1),
m, MAX(n-Count+1, 1),
SUM(INDEX(Amount, SEQUENCE(n-m+1,, m)))))))(C5:C28, E2)
Having said that, the function does not actually sum the data by group. Rather, it's summing the previous n rows in the range. If this is the expected result, great. If not, then another approach is needed. Cheers!
Thank you for finding the problem (and for the simplified solution. I had tried the MAX function but had a problem. I think that was due to the error you found. Thanks again.
I was looking for the previous n rows. That is what I defined as the group. Thanks for making sure.
Gary