Fluorite | Level 6

## Counting Horizontal backwards

Hello,

I am looking at counting variables backwards from a start point

The below examples shows what we have. I am looking at these 13 variables and hoping to count backwards to see how many Y's are consecutive from point 13 working backwards. E.g. ID1 = 1 as after this it hits a N, ID2 = 0 as Y comes after this point and ID 3 = 5.

data have;
input ID (var1-var13)(\$);
cards;
1 Y Y N N Y Y Y N Y Y Y N Y
2 Y Y Y Y Y Y Y Y Y Y N N N
3 Y N N N N Y N N Y Y Y Y Y
;
run;

Final Dataset is shown below

data want;
input ID (var1-var13)(\$) Consecutive_Y_from_Var13;
cards;
1 Y Y N N Y Y Y N Y Y Y N Y 1
2 Y Y Y Y Y Y Y Y Y Y N N N 0
3 Y N N N N Y N N Y Y Y Y Y 5
;
run;

Any help would be great,

Thank you.

1 ACCEPTED SOLUTION

Accepted Solutions
Onyx | Level 15

## Re: Counting Horizontal backwards

SAS has arrays:

``````data have;
input ID (var1-var13)(\$);
cards;
1 Y Y N N Y Y Y N Y Y Y N Y
2 Y Y Y Y Y Y Y Y Y Y N N N
3 Y N N N N Y N N Y Y Y Y Y
;
run;

data want;
set have;
array A{*} var1-var13;

Consecutive_Y_from_Var13 = 0;
do _N_ = dim(A) to 1 by -1;
if a[_N_] = "N" then leave;
else Consecutive_Y_from_Var13 + 1;
end;
run;``````

Bart

_______________
Polish SAS Users Group: www.polsug.com and communities.sas.com/polsug

"SAS Packages: the way to share" at SGF2020 Proceedings (the latest version), GitHub Repository, and YouTube Video.
Hands-on-Workshop: "Share your code with SAS Packages"
"My First SAS Package: A How-To" at SGF2021 Proceedings

SAS Ballot Ideas: one: SPF in SAS, two, and three
SAS Documentation

2 REPLIES 2
Tourmaline | Level 20

## Re: Counting Horizontal backwards

``````data have;
input ID (var1-var13)(\$);
cards;
1 Y Y N N Y Y Y N Y Y Y N Y
2 Y Y Y Y Y Y Y Y Y Y N N N
3 Y N N N N Y N N Y Y Y Y Y
;
run;

data want(drop = c);
set have;
c = cats(of var:);
Consecutive_Y_from_Var13 = lengthn(scan(c, -1, 'N'));
run;``````
Onyx | Level 15

## Re: Counting Horizontal backwards

SAS has arrays:

``````data have;
input ID (var1-var13)(\$);
cards;
1 Y Y N N Y Y Y N Y Y Y N Y
2 Y Y Y Y Y Y Y Y Y Y N N N
3 Y N N N N Y N N Y Y Y Y Y
;
run;

data want;
set have;
array A{*} var1-var13;

Consecutive_Y_from_Var13 = 0;
do _N_ = dim(A) to 1 by -1;
if a[_N_] = "N" then leave;
else Consecutive_Y_from_Var13 + 1;
end;
run;``````

Bart

_______________
Polish SAS Users Group: www.polsug.com and communities.sas.com/polsug

"SAS Packages: the way to share" at SGF2020 Proceedings (the latest version), GitHub Repository, and YouTube Video.
Hands-on-Workshop: "Share your code with SAS Packages"
"My First SAS Package: A How-To" at SGF2021 Proceedings

SAS Ballot Ideas: one: SPF in SAS, two, and three
SAS Documentation

Discussion stats
• 2 replies
• 415 views
• 0 likes
• 3 in conversation