Hello,
I have a data set with the following columns: ID ,Z_Reason1 ,Z_Reason2,Z_Reason3.
Z_Reason1 ,Z_Reason2,Z_Reason3 are binary variables with reasons for failure.
I want to calculate a new variable called Concatenate_Reasons that will get following values:
For ID=1 "Z_Reason1"
For ID=2 "Z_Reason1,Z_Reason2"
For ID=3 " "
FOR ID=4 "Z_Reason1,Z_Reason2,Z_Reason3"
and so on
As you can see the new variable will get value of concatenation of Binary variables names with value 1.
What is the way to do it please?
Data have;
Input ID Z_reason1 Z_reason2 Z_reason3;
CARDS;
1 1 0 0
2 1 1 0
3 0 0 0
4 1 1 1
5 0 0 1
6 1 0 0
7 1 0 0
8 0 1 0
;
Run;
Here what @ballardw describes in case it's not clear to you.
Data have;
Input ID Z_reason1 Z_reason2 Z_reason3;
CARDS;
1 1 0 0
2 1 1 0
3 0 0 0
4 1 1 1
5 0 0 1
6 1 0 0
7 1 0 0
8 0 1 0
;
data want;
set have;
length Concatenate_Reasons $100;
array z_reasons {*} z_reason:;
do i=1 to dim(z_reasons);
if z_reasons[i]=1 then
Concatenate_Reasons=catx(', ',Concatenate_Reasons,vname(z_reasons[i]));
end;
run;
or if it's only 3 variables you need to test:
data want;
set have;
length Concatenate_Reasons $100;
Concatenate_Reasons=
catx(', ',
ifc(Z_reason1=1,vname(Z_reason1),' '),
ifc(Z_reason2=1,vname(Z_reason2),' '),
ifc(Z_reason3=1,vname(Z_reason3),' ')
);
run;
What have you tried?
Almost trivial exercise in looping over 3 values in an array. The Vname function would help.
Here what @ballardw describes in case it's not clear to you.
Data have;
Input ID Z_reason1 Z_reason2 Z_reason3;
CARDS;
1 1 0 0
2 1 1 0
3 0 0 0
4 1 1 1
5 0 0 1
6 1 0 0
7 1 0 0
8 0 1 0
;
data want;
set have;
length Concatenate_Reasons $100;
array z_reasons {*} z_reason:;
do i=1 to dim(z_reasons);
if z_reasons[i]=1 then
Concatenate_Reasons=catx(', ',Concatenate_Reasons,vname(z_reasons[i]));
end;
run;
or if it's only 3 variables you need to test:
data want;
set have;
length Concatenate_Reasons $100;
Concatenate_Reasons=
catx(', ',
ifc(Z_reason1=1,vname(Z_reason1),' '),
ifc(Z_reason2=1,vname(Z_reason2),' '),
ifc(Z_reason3=1,vname(Z_reason3),' ')
);
run;
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.