Hi.
I'm using SAS 9.4 and have a programming question (I'm also quite new to SAS).
I want to "flag" all numbers from 4 to the first 0 in the diff_brunst variable by creating ones in the length variable, how do I do that?
This is the code I have been trying.
data c;
set b;
if diff_brunst = 4 then do length = 1 until (diff_brunst = 0);
end;
else length = 0;
run; Output (form a huge dataset).
In the parentheses is what I want to achieve.
Diff_brunst Length
0 0
0 0
0 0
0 0
0 0
2 0
3 0
4 1 (1)
5 0(1)
6 0(1)
-5 0(1)
0 0(1)
0 0
0 0
0 0
Use a retained variable:
data have;
input diff_brunst;
datalines;
0
0
0
0
0
2
3
4
5
6
-5
0
0
0
0
;
run;
data want;
set have;
retain length 0;
if diff_brunst = 4 then length = 1;
output;
if diff_brunst = 0 then length = 0;
run;
proc print data=want noobs;
run;
Note how I presented data in a data step with datalines.
Result:
diff_ brunst length 0 0 0 0 0 0 0 0 0 0 2 0 3 0 4 1 5 1 6 1 -5 1 0 1 0 0 0 0 0 0
PS the data step in itself constitutes a loop if a set, merge or infile with input statement is used.
@JA94 wrote:
Hi.
I'm using SAS 9.4 and have a programming question (I'm also quite new to SAS).
I want to "flag" all numbers from 4 to the first 0 in the diff_brunst variable by creating ones in the length variable, how do I do that?
This is the code I have been trying.
data c; set b; if diff_brunst = 4 then do length = 1 until (diff_brunst = 0); end; else length = 0; run;Output (form a huge dataset).
In the parentheses is what I want to achieve.
Diff_brunst Length
0 0
0 0
0 0
0 0
0 0
2 0
3 0
4 1 (1)
5 0(1)
6 0(1)
-5 0(1)
0 0(1)
0 0
0 0
0 0
Thanks, it worked!
Clearly it was not as complicated as I thought!
@JA94 wrote:
Thanks, it worked!
Clearly it was not as complicated as I thought!
My first statistics professor had a meta-theorem that was basically: You will never misunderstand a problem so as to make it simpler.
Probably overthinking it, just use a retained variable:
data a; set b; retain flag 0; if diff_brunst=4 then flag=1; if diff_brunst=0 and flag=1 then flag=0; run;
data have;
input diff_brunst;
datalines;
0
0
0
0
0
2
3
4
5
6
-5
0
0
0
0
;
run;
data want;
set have;
retain l 0;
if diff_brunst=4 then l=1;
else if lag(diff_brunst)=0 and l then l=0;
run;
Hi @JA94 Looks like your question has been answered by @Kurt_Bremser Requesting you to please mark that solution and close the thread
It's finally time to hack! Remember to visit the SAS Hacker's Hub regularly for news and updates.
Learn how use the CAT functions in SAS to join values from multiple variables into a single value.
Find more tutorials on the SAS Users YouTube channel.
Ready to level-up your skills? Choose your own adventure.