DATA Step, Macro, Functions and more

Simple data management question

Reply
New Contributor
Posts: 2

Simple data management question

I'm going nuts trying to figure out where my coding error is. Can anyone tell me what I'm doing wrong?

 
I'm trying to define a new variable called "HB_DLPP1". HB_DLPP1 can be =0 (no) and 1(yes) or -99 (unmeasured) or . (missing). This variable incorporates another variable called "DLPP1". DLPP1 can be = 1, =2, =-99, or =. When DLPP1 is = -99, I want SAS to use the information from a different variable called "Pdet1" to define HB_DLPP1. Pdet1 can be =1, =2, =-99, or = . 
 
I wrote the following code:
 
If DLPP1 = 1 then HB_DLPP1 = 0;
Else if DLPP1 = 2 then HB_DLPP1 = 1;
Else if DLPP1 = -99 AND Pdet1 = 1 then HB_DLPP1 = 0;
Else if DLPP1 = -99 AND Pdet1 = 2 then HB_DLPP1 = 1;
Else HB_DLPP1 = .;
 
It works perfectly except for the highlighted line, where I want HB_DLPP1 = 0 bc DLPP1 = -99 and Pdet = 1. 
What do I need to change to make this assign the correct values??
 
Super User
Super User
Posts: 7,955

Re: Simple data management question

Its always a good idea to post test data as a datastep in the post to show what you have, and example of what you want out.  Its very hard to tell from what you have posted, anything which is happening.  I would maybe write it like this:

data want;
  set have;
  select (dlpp1);
    when (1) hb_dlpp1=0;
    when (2) hb_dlpp1=1;
    when (-99) hb_dlpp1=ifn(pdet1=1,0,1);
    otherwise hb_dlpp1=.;
  end;
run;

Note how I don't use mixed case.

New Contributor
Posts: 2

Re: Simple data management question

MANY THANKS FOR YOUR HELP! This fixed the specific problem, but then it handled -99 and . differently. When both are -99 hb_dlpp1 should = -99, and when one is -99 and the other ., it should = . 9 (see below):

 

 

I forced it to give me the right results by adding the additional  2 lines of code, but is there a more elegant way to do this?

 

if dlpp1 = -99 AND pdet1 = . then hb_dlpp1 = .;

if dlpp1 = -99 and pdet1 = -99 then hb_dlpp1 = -99;

 

 

 

Super User
Super User
Posts: 7,955

Re: Simple data management question

Just update it to reflect your logic:

data want;
  set have;
  select (dlpp1);
    when (1) hb_dlpp1=0;
    when (2) hb_dlpp1=1;
    when (-99) do;
      if pdet=1 then hbdlpp1=1;
if pdet=2 then hpdlpp1=0;
if pdet=. then hdlpp1=.;
if pdet=-99 then hldpp1=-99; end; otherwise hb_dlpp1=.; end; run;
Super User
Posts: 5,509

Re: Simple data management question

The rest of us have now officially joined you (going nuts, that is).  There's nothing wrong with the code you posted.  Perhaps there's something going on in the larger context of the DATA step since you posted just a portion of the DATA step.

Ask a Question
Discussion stats
  • 4 replies
  • 81 views
  • 0 likes
  • 3 in conversation