BookmarkSubscribeRSS Feed
ibsulkim
Obsidian | Level 7

Hi,

I believe there must be a simple way to copy value in the next row(observation) within the same column.

Data set can be simplifies as below:

[original data set]

V1  V2  V3  V4  V5

aa   bb  cc  dd   ee

mk  jk   as   rd   as

aa   bb  cc  dd   ee

re    te   sf   er   qw

[goal data set] 

V1  V2  V3  V4   V5

mk   bb  as   dd  ee

mk   jk   as   rd   as

re    bb   sf   dd   ee

re    te    sf   er   qw

I would like to change the value 'aa' into the value in the next row

and change the value 'cc' into the value in the next row.

Any comment or suggestion will be greatly appreciated.

Thanks,

Minsoo

4 REPLIES 4
Tom
Super User Tom
Super User

This is a common problem.  For example look at this thread.

http://listserv.uga.edu/cgi-bin/wa?A2=ind1012B&L=sas-l&P=R14426&D=0

For your problem you could try:

data want ;

   set have nobs=nobs ;

   next1 = _n_ + 1;

   if V1 in ('aa','cc') and _n_ < nobs then set have(keep=V1) point=next1 ;

run;

You will need to expand this to cover all the variables that you want to "move up".

art297
Opal | Level 21

A slight variation on Tom's suggested solution:

data want;

   set have;

   next1 = _n_ + 1;

   if mod(_n_,2) eq 1 then set have(keep=V1) point=next1 ;

run;

Ksharp
Super User

Or use merge skill

data temp;
 input (V1-V5 ) ($) ;
cards;
aa   bb  cc  dd   ee
mk  jk   as   rd   as
aa   bb  cc  dd   ee
re    te   sf   er   qw
;run;
data want;
 merge temp temp(firstobs=2 keep=v1 v3 rename=(v1=_v1 v3=_v3));
 if v1 eq 'aa' then v1=_v1;
 if v3 eq 'cc' then v3=_v3;
 drop _:;
run;

Ksharp

manojinpec
Obsidian | Level 7

One other method:

  data temp;
   input (V1-V5 ) ($) ;
  cards;
  aa   bb  cc  dd   ee
  mk  jk   as   rd   as
  aa   bb  cc  dd   ee
  re    te   sf   er   qw
  ;run;

  data temp1;
set temp;
N=_n_;
run;
proc sort data=temp1 ;
by descending n;
run;


data temp1;
set temp1; lagv1=lag(v1);lagv3=lag(v3);
if v1='aa' then v1=lagv1;if v3='cc' then v3=lagv3;
run;


  proc sort data =temp1 out=temp(drop=n lagv1 lagv3);
by n;
run;

hackathon24-white-horiz.png

2025 SAS Hackathon: There is still time!

Good news: We've extended SAS Hackathon registration until Sept. 12, so you still have time to be part of our biggest event yet – our five-year anniversary!

Register Now

How to Concatenate Values

Learn how use the CAT functions in SAS to join values from multiple variables into a single value.

Find more tutorials on the SAS Users YouTube channel.

SAS Training: Just a Click Away

 Ready to level-up your skills? Choose your own adventure.

Browse our catalog!

Discussion stats
  • 4 replies
  • 9859 views
  • 1 like
  • 5 in conversation