BookmarkSubscribeRSS Feed
TurnTheBacon
Fluorite | Level 6

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.

2 REPLIES 2
Tom
Super User Tom
Super User

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;

LinusH
Tourmaline | Level 20

It would probably be easier if you used the MOD function:

if mod(_n_) = 0 then new_row = value2;

else new_row = value1;

Data never sleeps

sas-innovate-2024.png

Join us for SAS Innovate April 16-19 at the Aria in Las Vegas. Bring the team and save big with our group pricing for a limited time only.

Pre-conference courses and tutorials are filling up fast and are always a sellout. Register today to reserve your seat.

 

Register now!

How to connect to databases in SAS Viya

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.

Discussion stats
  • 2 replies
  • 670 views
  • 7 likes
  • 3 in conversation