New Contributor
Posts: 2

# why I am getting this answer?

data test;
input x;
datalines;
1
2
3
4
5
;
run;
proc print data=test;
run;
data test1;
set test;
if x=1 then y=10;
if x=2 then y=20;
if x=3 then y=30;
if x=4 then y=40;
else y=5000;
run;

Answer which i am getting is:

X              Y

 1 1 5000
 2 2 5000
 3 3 5000
 4 4 40
 5 5 5000

Can someone please explain this to me? I am able to solve "else if" but facing problem in this type.

Super User
Posts: 22,857

## Re: why I am getting this answer?

[ Edited ]

Each IF statement is evaluated independently, but along with each ELSE.

Only you’re last IF is connected to the ELSE condition, The ELSE in this case resets all the previous results because they’re not 4.

Change all of your IF to ELSE IF, except the first one, or use a SELECT statement instead.

mohitraj4u wrote:

data test;
input x;
datalines;
1
2
3
4
5
;
run;
proc print data=test;
run;
data test1;
set test;
if x=1 then y=10;
if x=2 then y=20;
if x=3 then y=30;
if x=4 then y=40;
else y=5000;
run;

Answer which i am getting is:

X              Y

 1 1 5000
 2 2 5000
 3 3 5000
 4 4 40
 5 5 5000

Can someone please explain this to me? I am able to solve "else if" but facing problem in this type.

Super User
Posts: 13,066

## Re: why I am getting this answer?

And for a different way to evaluate multiple values of a variable:

```data test1;
set test;
select (x);
when (1) y=10;
when (2) y=20;
when (3) y=30;
when (4) y=40;
otherwise y=5000;
end;
run;```
PROC Star
Posts: 1,340

## Re: why I am getting this answer?

PDV understanding is very important and handy: try using put like the following to gauge what's happening

data test;
input x;
datalines;
1
2
3
4
5
;
run;

data test1;
set test;
if x=1 then y=10;
put x= y=;
if x=2 then y=20;
put x= y=;
if x=3 then y=30;
put x= y=;
if x=4 then y=40;
else y=5000;
put x= y=;
run;

x=1 y=10
x=1 y=10
x=1 y=10
x=1 y=5000
x=2 y=.
x=2 y=20
x=2 y=20
x=2 y=5000
x=3 y=.
x=3 y=.
x=3 y=30
x=3 y=5000
x=4 y=.
x=4 y=.
x=4 y=.
x=4 y=40
x=5 y=.
x=5 y=.
x=5 y=.
x=5 y=5000

Super User
Posts: 22,857

## Re: why I am getting this answer?

@novinosrin I would suggest adding some text to your PUT statement, such as CHECK1, CHECK2. It makes it easier to trace. Your solution is a great suggestion on how to view what’s happening.

novinosrin wrote:

data test1;
set test;
if x=1 then y=10;
put 'CHECK1' x= y=;
if x=2 then y=20;
put 'CHECK2' x= y=;
if x=3 then y=30;
put x= y=;
if x=4 then y=40;
else y=5000;
put x= y=;
run;

Highlighted
PROC Star
Posts: 1,340

## Re: why I am getting this answer?

I totally agree, making it descriptive makes it easy to comprehend even by non technical audiences. My professor says that to me all the time and yet i lack attention to detail. Good one indeed!

Discussion stats
• 5 replies
• 275 views
• 6 likes
• 4 in conversation