I have a data set with 80 rows. For every set of 4 rows, I want to insert one kind of value into the first three rows, and a different value into the fourth row. I first figured the code might be something like this:
data &_output;
set work.testdata;
while not last row;
if _n_ <= 3 then do;
new_row = value1;
end;
else if _n_ = 4 then do;
new_row = value2;
_n_ = 1;
end;
end;
run;
I just realized I'm misusing _n_ though, and need to reconsider it. Perhaps I can use a custom count variable. In any case, my question is, how do I do the "while not last row" part of the code correctly? Actually, the last row should preferably be included.
Thanks for your attention.
Why not use the MOD function to test if you are on the 4th observation?
That way you can adjust the value of the new variable you are creating.
Note that normally new variables as referred to as columns instead of rows. If you actually meant to create new observations (aka new rows) then the code will be different, but the logic for finding every fourth observation would be the same.
data want;
set have;
if 0=mod(_n_,4) then new_variable=value2;
else new_variable=value1;
run;
It would probably be easier if you used the MOD function:
if mod(_n_) = 0 then new_row = value2;
else new_row = value1;
Registration is now open for SAS Innovate 2025 , our biggest and most exciting global event of the year! Join us in Orlando, FL, May 6-9.
Sign up by Dec. 31 to get the 2024 rate of just $495.
Register now!
Need to connect to databases in SAS Viya? SAS’ David Ghan shows you two methods – via SAS/ACCESS LIBNAME and SAS Data Connector SASLIBS – in this video.
Find more tutorials on the SAS Users YouTube channel.