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.
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
How about
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;
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
Registration is open! SAS is returning to Vegas for an AI and analytics experience like no other! Whether you're an executive, manager, end user or SAS partner, SAS Innovate is designed for everyone on your team. Register for just $495 by 12/31/2023.
If you are interested in speaking, there is still time to submit a session idea. More details are posted on the website.
Learn the difference between classical and Bayesian statistical approaches and see a few PROC examples to perform Bayesian analysis in this video.
Find more tutorials on the SAS Users YouTube channel.