BookmarkSubscribeRSS Feed
Sama1
Calcite | Level 5
Hi
Recently I started learning SAS , I need help with retain statement
I have the following dataset

Id xyz
A 1
A 2
A 3
A 4
B 1
B 2
B 3
B 4

I want to retain second observation in each group and reassign its value in 4th observation ..like

Id xyz
A 1
A 2
A 3
A 2
B 1
B 2
B 3
B 2

Thanks
5 REPLIES 5
Sama1
Calcite | Level 5
 
novinosrin
Tourmaline | Level 20

A nice home work 🙂

 

 

data have;
input Id $ xyz;
datalines;
A 1
A 2
A 3
A 4
B 1
B 2
B 3
B 4
;

data want;
do _n_=1 by 1 until(last.id);
set have;
by id;
if _n_=2 then _t=xyz;
else if _n_=4 then xyz=_t;
output;
end;
drop _:;
run;

novinosrin
Tourmaline | Level 20

Or since you desire traditional retain statement method, here you go:

 

data want;
set have;
by id;
retain _t;
if first.id then n=0;
n+1;
if n=2 then _t=xyz;
else if n=4 then xyz=_t;
drop n _t;
run;

Sama1
Calcite | Level 5
Thank you very much 👍☺️
Reeza
Super User

Please mark the appropriate response (not this one) as the correct answer so that we know your question is resolved. 

 

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 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.

Click image to register for webinarClick image to register for webinar

Classroom Training Available!

Select SAS Training centers are offering in-person courses. View upcoming courses for:

View all other training opportunities.

Discussion stats
  • 5 replies
  • 782 views
  • 1 like
  • 3 in conversation