Hello
In following row data for each customer there is information about number of months that he was exposed to illness.
What is the way to write this code in a shorter and more useful way.
Also in the real data maximum number of months of exposition is 18 (and not 6).
I would like to know how to write a more general code that work also for 18 months.
Data Rawdata;
Input ID No_Mon_expose;
cards;
1 6
2 3
3 3
4 4
5 2
6 1
7 6
8 3
9 2
10 6
;
run;
Data wanted;
set Rawdata;
if No_Mon_expose=6 then do;
Ind_Expose_Mon1=1;
Ind_Expose_Mon2=1;
Ind_Expose_Mon3=1;
Ind_Expose_Mon4=1;
Ind_Expose_Mon5=1;
Ind_Expose_Mon6=1;
end;
else if No_Mon_expose=5 then do;
Ind_Expose_Mon1=1;
Ind_Expose_Mon2=1;
Ind_Expose_Mon3=1;
Ind_Expose_Mon4=1;
Ind_Expose_Mon5=1;
Ind_Expose_Mon6=0;
end;
else if No_Mon_expose=4 then do;
Ind_Expose_Mon1=1;
Ind_Expose_Mon2=1;
Ind_Expose_Mon3=1;
Ind_Expose_Mon4=1;
Ind_Expose_Mon5=0;
Ind_Expose_Mon6=0;
end;
else if No_Mon_expose=3 then do;
Ind_Expose_Mon1=1;
Ind_Expose_Mon2=1;
Ind_Expose_Mon3=1;
Ind_Expose_Mon4=0;
Ind_Expose_Mon5=0;
Ind_Expose_Mon6=0;
end;
else if No_Mon_expose=2 then do;
Ind_Expose_Mon1=1;
Ind_Expose_Mon2=1;
Ind_Expose_Mon3=0;
Ind_Expose_Mon4=0;
Ind_Expose_Mon5=0;
Ind_Expose_Mon6=0;
end;
else if No_Mon_expose=1 then do;
Ind_Expose_Mon1=1;
Ind_Expose_Mon2=0;
Ind_Expose_Mon3=0;
Ind_Expose_Mon4=0;
Ind_Expose_Mon5=0;
Ind_Expose_Mon6=0;
end;
Run;
one way
data want;
set Rawdata;
array Ind_Expose_Mon {18} (18*0);
do _N_=1 to No_Mon_expose;
Ind_Expose_Mon [_N_] = 1;
end;
run;
Hi @Ronein
Here is a way to achieve this using an array:
data Rawdata_long;
set Rawdata;
array Ind_Expose_Mon (6); /* replace by 18 */
do i=1 to dim(Ind_Expose_Mon);
if i<=No_Mon_expose then Ind_Expose_Mon(i)=1;
else Ind_Expose_Mon(i)=0;
end;
drop i;
run;
very likely making a wide data set will make later steps harder, depending on how this data is to be used.
You should be able to do this with an array. Take advantage of the fact that SAS evaluate boolean expressions to 0 or 1 to make setting the value easier.
data wanted;
set Rawdata;
array Ind_Expose_Mon [18];
do index=1 to dim(Ind_Expose_Mon);
Ind_Expose_Mon[index]= (index <= No_Mon_expose) ;
end;
drop index;
run;
Whether you want to or not is a different question.
Are you ready for the spotlight? We're accepting content ideas for SAS Innovate 2025 to be held May 6-9 in Orlando, FL. The call is open until September 25. Read more here about why you should contribute and what is in it for you!
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.