array help

Reply
New Contributor
Posts: 4

array help


Hi,

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;

regtot(12) reg1-reg12;

i = 1 TO 12;

if (regtot(i)~=1) and (regtot(i ~=0then 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;  

end;

run;

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.

Super User
Super User
Posts: 7,042

Re: array help

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;

cards;

0 0 0 0 0 0

3 0 1 2 0 0

2 0 0 0 2 0

1 1 1 1 1 1

;;;;

New Contributor
Posts: 4

Re: array help

Hi Tom,

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

Super User
Posts: 11,343

Re: array help

data look5;

     set look4;

   regt = 2*(0<whichn(2,of reg1-reg12))

          + 1*(0<whichn(1,of reg1-reg12))

   ;

run;

New Contributor
Posts: 4

Re: array help

thank you so much!!! That worked!!

Super User
Posts: 10,028

Re: array help

Those variables only have three value 0 1 2 ?

Super User
Super User
Posts: 7,042

Re: array help

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.

Ask a Question
Discussion stats
  • 6 replies
  • 292 views
  • 0 likes
  • 4 in conversation