Hi,
I want to create a dataset that looks like data "want" below, for id 1-100. This is for an exercise so the values don't matter, but the data structure needs to follow these rules:
I have tried a few approaches, but I am running into issues. For example, this attempt goes from wide to long. Within each id, how do I set values after 1 to missing?
Thanks in advance!
data sim1;
do id=1 to 100;
year0=0;
year1=1;
year2=2;
year3=3;
year4=4;
year5=5;
output; end;
run;
proc transpose data=sim1 out=sim2;
by id;
run;
data sim3;
set sim2 (rename=(COL1=year));
y=rand("BINOMIAL", 0.2, 1);
drop _name_;
run;
data want;
input id y time;
datalines;
1 1 0
1 . 1
1 . 2
1 . 3
1 . 4
1 . 5
2 0 0
2 0 1
2 0 2
2 1 3
2 . 4
2 . 5
;
run;
In a DATA Step use a retained flag variable to track the occurrence of y=1 in the ID group.
Set the y value to missing when the flag is active.
In this example, because y is 0 or 1, the flag can be assigned to the y value (up to the point at which y=1). After flag is assigned 1 the else never occurs again (within the BY group.)
data want;
set sim3;
by id;
if first.id then flag = 0;
if flag then
y = .;
else
flag = y;
retain flag; drop flag;
run;
In a DATA Step use a retained flag variable to track the occurrence of y=1 in the ID group.
Set the y value to missing when the flag is active.
In this example, because y is 0 or 1, the flag can be assigned to the y value (up to the point at which y=1). After flag is assigned 1 the else never occurs again (within the BY group.)
data want;
set sim3;
by id;
if first.id then flag = 0;
if flag then
y = .;
else
flag = y;
retain flag; drop flag;
run;
Essentially, once flag is set if flag then y=.; clause will always happen -- flag will never change value until the next first.id=1 occurs
It's a matter of figuring out a 'state machine' that produces the values relevant to your processing needs.
Let's unroll that return to top.
SAS Innovate 2025 is scheduled for May 6-9 in Orlando, FL. Sign up to be first to learn about the agenda and registration!
Need to connect to databases in SAS Viya? SAS’ David Ghan shows you two methods – via SAS/ACCESS LIBNAME and SAS Data Connector SASLIBS – in this video.
Find more tutorials on the SAS Users YouTube channel.