## Cumulative count in arrays

Solved
Occasional Contributor
Posts: 8

# Cumulative count in arrays

the aim of this Question is Counting number of Delinquency during last 12 month But the trick is how to start cumulative count from right to left when find 1 and stop Counting when find 0 Then start counting again when it finds 1

like row number 1 result part .

example :

Data test ;
input A1 A2 A3 A4 A5 A6 A7 A8;
Datalines ;
1 0 1 1 0 1 1 1
1 1 0 0 0 1 1 0
1 1 1 1 1 1 0 0
0 0 0 1 0 1 1 1
1 0 1 1 1 0 0 0
0 1 0 1 0 1 1 1
;
Run ;

The result should be :

B1     B2    B3    B4    B5    B6    B7    B8
1       0      2       1      0      3      2      1
2       1      0       0      0      2      1      0
6       5      4       3      2      1      0      0
0       0      0       1      0      3      2      1
1       0      3       2      1      0      0      0
0       1      0       1      0      3      2      1

Accepted Solutions
Solution
‎04-10-2017 04:52 AM
Super User
Posts: 9,802

## Re: Cumulative count in arrays

Just to add to @KurtBremser, you don't actually need the counter, just go in reverse from second to end one and then add next cell to the current:

Data test ;
input A1 A2 A3 A4 A5 A6 A7 A8;
Datalines ;
1 0 1 1 0 1 1 1
1 1 0 0 0 1 1 0
1 1 1 1 1 1 0 0
0 0 0 1 0 1 1 1
1 0 1 1 1 0 0 0
0 1 0 1 0 1 1 1
;
Run ;

data want;
set test;
array vals{*} a:;
do i=dim(vals)-1 to 1 by -1;
if vals{i}=1 then vals{i}=vals{i+1}+1;
end;
run;

All Replies
Super User
Posts: 10,530

## Re: Cumulative count in arrays

Declare array for the A and B variables.

Set a counter variable to zero.

In a do loop that counts down from dim(array) to 1, do

- if A(i) is zero, set counter to zero

- if A(i) is 1, add 1 to counter

- set B(i) to counter

---------------------------------------------------------------------------------------------
Maxims of Maximally Efficient SAS Programmers
How to convert datasets to data steps
How to post code
Solution
‎04-10-2017 04:52 AM
Super User
Posts: 9,802

## Re: Cumulative count in arrays

Just to add to @KurtBremser, you don't actually need the counter, just go in reverse from second to end one and then add next cell to the current:

Data test ;
input A1 A2 A3 A4 A5 A6 A7 A8;
Datalines ;
1 0 1 1 0 1 1 1
1 1 0 0 0 1 1 0
1 1 1 1 1 1 0 0
0 0 0 1 0 1 1 1
1 0 1 1 1 0 0 0
0 1 0 1 0 1 1 1
;
Run ;

data want;
set test;
array vals{*} a:;
do i=dim(vals)-1 to 1 by -1;
if vals{i}=1 then vals{i}=vals{i+1}+1;
end;
run;
Occasional Contributor
Posts: 8