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

Don't miss out on SAS Innovate - Register now for the FREE Livestream!

Can't make it to Vegas? No problem! Watch our general sessions LIVE or on-demand starting April 17th. Hear from SAS execs, best-selling author Adam Grant, Hot Ones host Sean Evans, top tech journalist Kara Swisher, AI expert Cassie Kozyrkov, and the mind-blowing dance crew iLuminate! Plus, get access to over 20 breakout sessions.

 

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
  • 679 views
  • 7 likes
  • 3 in conversation