Domanda

Struggling to get this If/Then/Else statement not working. I have two columns: Variable and Value. Variable has the name of the variable and Value has all the potential codes that could be associated with that Variable.

Example:

Variable     Value
Gender         F
Gender         M

I want to create a field called "Flag" and if the value isn't among the list of values, it should flag that field; otherwise, leave that field blank

data Want;
length 
Variable $40.
Value $40.
Flag $8.;
set Have (keep = Variable Value);
if (Variable = 'Gender' and Value ^= 'M') then Flag = 'UnkCode'; else Flag="";
if (Variable = 'Gender' and Value ^= 'F') then Flag = 'UnkCode'; else  Flag="";
if (Variable = 'Gender' and Value ^= 'O') then Flag = 'UnkCode'; else Flag="";
if (Variable = 'Gender' and Value ^= 'U') then Flag = 'UnkCode'; else Flag="";
run;
quit;

The dataset I'm using has only has two values for Gender: F and M. For whatever reason, the flag field in both lines has "UnkCode"

Any idea what I'm doing wrong?

È stato utile?

Soluzione

Just to be, possibly, a little more clear: your if statements are evaluated sequentially.

So for your first observation, Flag will be initially set to "", as ('M' = 'M'). However, Flag is then overwritten by your subsequent if statements, and as ('M' ^= 'F'), Flag is overwritten, and takes the value 'UnkCode'.

In addition to Keni's use of an in statement (which is better than the code I am about to suggest), you could also do the following (which may help you understand if statements better).

if (Variable = 'Gender' and Value = 'M') then Flag = "";
else if (Variable = 'Gender' and Value = 'F') then Flag = "";
else if (variable = 'Gender' and Value = 'O') then Flag = "";
else if (Variable = 'Gender' and Value = 'U') then Flag = "";
else if (Variable = 'Gender') then Flag = 'UnkCode';

I might also suggest that instead of having a variable named 'Variable', with a value of 'Gender', you simply have a variable named 'Gender' with a value of 'F' or 'M'. While there are certainly specific circumstances in which you would not want to create your dataset this way, they are relatively few and far between.

Altri suggerimenti

I put all the IF conditions in one statement and it worked.

data Want;
      length Variable $40. Value $40. Flag $8.;
      set Have (keep = Variable Value);
      If (Variable = 'Gender' and Value in ('F','M','O','U')) then Flag =" "; 
         else Flag = 'UnkCode'; 
run;
quit;

For multiple variables to flag for... this should work.

data Want;
    length Variable $40. Value $40. Flag $8.;
    set Have (keep = Variable Value);
    Flag = 'UnkCode';
    if (Variable = 'Gender' and Value in ('F','M','O','U')) then Flag =" "; 
    else if (Variable = 'Race' and Value in ('B','A')) then Flag =" ";  
run;
quit;
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top