why repeated observations??

Solved
Frequent Contributor
Posts: 79

why repeated observations??

Hi Experts,

I am using below mentioned code but getting repeated observation and for first observation OUT variable has missing value...WHY??

data new ;
do i=1 to 10;
if mod(i,2)=0 then out=i;
output;
end;
run;

OUTPUT:

Obs     i    out
1     1      .
2     2      2
3     3      2
4     4      4
5     5      4
6     6      6
7     7      6
8     8      8
9     9      8
10    10     10

Accepted Solutions
Solution
‎09-07-2016 04:21 PM
Super Contributor
Posts: 543

Re: why repeated observations??

Then do something like this:

data new ;
do i=1 to 10;
if mod(i,2)=0 then output;
end;
run;
proc print;run;

All Replies
Super User
Posts: 5,876

Re: why repeated observations??

Perhaps you need an else statement?
Data never sleeps
Super Contributor
Posts: 543

Re: why repeated observations??

Hi.

if you go through the do-loop, you will see how values get assigned to out:

for i = 1, mod(i,2) = 0 is False, so out = .;

output this record;

for i = 2, mod(i,2) = 0 is true, so out = 2;

output this record;

for i = 3, mod(i,2) = 0 is False, so out = 2;

output this record;

for i = 4, mod(i,2) = 0 is true, so out = 4;

output this record;

if you want out to take a different value for the cases when mod(i,2) is false, then assign it.

Something like,

if mod(i,2) = 0 then out = i;else out = .;

I hope this helps.

Anca.

Frequent Contributor
Posts: 79

Re: why repeated observations??

i simply want every second obs only.
Solution
‎09-07-2016 04:21 PM
Super Contributor
Posts: 543

Re: why repeated observations??

Then do something like this:

data new ;
do i=1 to 10;
if mod(i,2)=0 then output;
end;
run;
proc print;run;

Frequent Contributor
Posts: 79

Re: why repeated observations??

hi AncaTilea,
why for i=3 var OUT has a valur 2???
Super Contributor
Posts: 543

Re: why repeated observations??

because it carries down from the information above...

You never told SAS to change the value...

Super User
Posts: 23,689

Re: why repeated observations??

Rahul_SAS wrote:
hi AncaTilea,
why for i=3 var OUT has a valur 2???

This wouldn't happen a data step that was using an input data set. In that case it would reset to missing, because each new line sets all new variables to missing unless you have a retain.

However, in your case you have no input data set and are looping so it's really considered a single step and the values are retained until you reset them.

Super User
Posts: 23,689

Re: why repeated observations??

Comment your code to help understand:

data new ; *Create a new dataset called new;
do i=1 to 10; *Loop from 1 to 10;
if mod(i,2)=0 then out=i; *If number is even then assign counter, i, to variable out.
output; *output, since no filters this would be all observations;
end; *end of loop;
run; *end of datastep;