DATA Step, Macro, Functions and more

Cumulative count in arrays

Accepted Solution Solved
Reply
Occasional Contributor
Posts: 8
Accepted Solution

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

 

Your help is highly appreciated 


Accepted Solutions
Solution
‎04-10-2017 04:52 AM
Super User
Super User
Posts: 7,942

Re: Cumulative count in arrays

Posted in reply to Amr_Alaaeldin

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;

View solution in original post


All Replies
Super User
Posts: 7,762

Re: Cumulative count in arrays

Posted in reply to Amr_Alaaeldin

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
Solution
‎04-10-2017 04:52 AM
Super User
Super User
Posts: 7,942

Re: Cumulative count in arrays

Posted in reply to Amr_Alaaeldin

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

Re: Cumulative count in arrays

Thanks For Quick Reply
☑ This topic is solved.

Need further help from the community? Please ask a new question.

Discussion stats
  • 3 replies
  • 166 views
  • 4 likes
  • 3 in conversation