03-11-2015 12:43 PM
Im hoping to create an array (regtot(1) reg1-reg12) across 12 variables in order to create a new variable with the following conditions:
if the number 1 or 2 appear in any of the 12 variables or array then the new variable (regt) equals 3
if the number 2 appears on its own (e,g no 1s across the 12 variables but can have 0s) then new variable (regt) equals 2
if the number 1 appears on its own (e,g no 2s across the 12 variables but can have 0s) then new variable (regt) equals 1
if there are just zeros across the rows then new variable equals 0
this is the code I'm using:
look5; set look4;
i = 1 TO 12;
if (regtot(i)~=1) and (regtot(i ~=0) then regt=2;
else if (regtot(i)~=2) and (regtot(i)~=0) then regt=1;
else if (regtot(i)= 1) and (regtot(i)= 2) then regt=3;
else regt = 0;
This does not seem to be working - the regt variable is populated with 2 and 1s and missing values, no 3s or 0s. Any help or ideas would be super helful.
03-11-2015 12:53 PM
No need for any array.
Here is logic using 5 variables to save me time typing more data.
data test ;
input expect reg1-reg5 ;
regt = 2*(0<whichn(2,of reg1-reg5))
+ 1*(0<whichn(1,of reg1-reg5))
put regt expect reg1-reg5;
0 0 0 0 0 0
3 0 1 2 0 0
2 0 0 0 2 0
1 1 1 1 1 1
03-11-2015 04:36 PM
Thanks so much for your time and help on this. that's super smart - but a bit over my head at this stage. Im working from a datafile of over 20000 obs so not sure I can use a card statement? I'm not too familiar with this (cards) and not sure how to run it on my by dataset. Ive tried your code but it just overrides my existing values in variables reg1-12
03-11-2015 05:36 PM
The CARDS and the INPUT statement are just so I could create some sample data to test the program.
In your case if you already have a data set then you can use a SET statement to read in the values. Or you could just add the assignment statement to an existing data step that you have that is manipulating this data.
The reason the statement works is because SAS will evaluate a logic test like (0 < A) to either 1 (true) or 0 (false).
The WHICHN() function will return which item number in the list is equal to the requested value. It will return a 0 when there is no match.