'SAS- How Code an array from previous set of variables
I need to create a new variable in which is comprised of a list of other variables found in my dataset.
HAD1 (1=yes 2=no 9=unknown),
HAF10 (1=yes 2=no 9=unknown),
HAC1C (1=yes 2=no 9=unknown),
and HAC1D (1=yes 2=no 9=unknown)
to add up the number of health conditions an individual has. I also want to set all 9 to equal "." My new variable will be named CC4
CC4 =
(0=no conditions,
1=one condition,
2=two conditions,
3=three conditions,
4=four conditions,
.=any condition appears missing)
How do I code it in the correct way and add it to my dataset?
I only wrote this:
data dataset;
set dataset;
*use arrays to create clean, re-coded versions of variables;
array code1 [4] HAD1 HAF10 HAC1C HAC1D;
array code2 [4] diabetes hattack hfailure stroke;
do new= 1 to 4;
if code1 [new] = 1 then code2 [new] = 1;
*keep all 1's as 1's;
else if code1 [new] = 2 then code2 [new] = 2;
*keep all 2's as 2's;
else if code1 [new] = 9 then code2 [new] = .;
*make all 9's into .'s;
end;
drop new;
*create summation variable;
cc4=HAD1+HAF10+HAC1C+HAC1D;
Solution 1:[1]
You don't need to recode to count.
You can take advantage of SAS evaluating boolean expressions to 1 for TRUE and 0 for FALSE.
data want;
set have;
cc4 = (HAD1=1)+(HAF10=1)+(HAC1C=1)+(HAC1D=1);
run;
PS Do not overwrite your input data by using the same dataset name in the DATA and SET statements. It will make it hard to correct coding mistakes.
Solution 2:[2]
If you want new names for the original code variables, use RENAME
If you want new names and the original code variables, probably shouldn't
If you only want the cc4 result, you can use the fact of a single digit code for meaning to compute your condition count when all conditions assert a yes/no state.
Example:
data have;
do code1 = 1,2,9;
do code2 = 1,2,9;
do code3 = 1,2,9;
do code4 = 1,2,9;
output;
end;end;end;end;
run;
data want;
set have;
codes = cats(code1,code2,code3,code4);
drop codes;
cc4 = ifn(index(codes,'9'),.,count(codes,'1'));
run;
In your case replace code1,code2,code3,code4
with HAD1,HAF10,HAC1C,HAC1D
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Tom |
Solution 2 | Richard |