BookmarkSubscribeRSS Feed
🔒 This topic is solved and locked. Need further help from the community? Please sign in and ask a new question.
efi88
Fluorite | Level 6

Hi, 

 

I'm trying to calculate new variables based on other variables from different row of specific value. 

For example: 

 

my_data:

name string value

namestringvalue
abaaaaaa12
bababbbbb84
cacacccc65
gagaddddd52

 

 

wanted_data

name stringvaluediff
abaaaaaa12 
bababbbbb8472
cacacccc6544
gagaddddd5240

 

The calculation of the new variable diff:

0
84-12
65-12
52-12

 

Please advice,

Thank you!

1 ACCEPTED SOLUTION

Accepted Solutions
PeterClemmensen
Tourmaline | Level 20
data have;
input name $	string $	value;
datalines;
aba	aaaaa	12
baba	bbbbb	84
caca	cccc	65
gaga	ddddd	52
;

data want(drop=v);
   set have;
   if _N_=1 then v=value;
   diff=value-v;
   retain v;
run;

View solution in original post

5 REPLIES 5
tomrvincent
Rhodochrosite | Level 12
use the 'retain' command.
novinosrin
Tourmaline | Level 20
data have;
input name$	string$	value;
cards;
aba	aaaaa	12
baba	bbbbb	84
caca	cccc	65
gaga	ddddd	52
;

data want;
set have;
if _n_=1 then do; t=value;diff=0;end;
else diff=value-t;
retain t;
drop t;
run;
novinosrin
Tourmaline | Level 20

@efi88   Also, you could use a conditional set to mimic retain

 

data have;
input name$	string$	value;
cards;
aba	aaaaa	12
baba	bbbbb	84
caca	cccc	65
gaga	ddddd	52
;
data want;
set have;
if _n_=1 then set have(keep=value rename=(value=t));
diff=value-t;
drop t;
run;

 

 

pb82477
Fluorite | Level 6

efi88: As has already been stated, the retain statement should be a big help.

 

However, it appears that you have an error in your  'wanted data'.  For name 'caca', according to your specified formula, the result should be 53 (65-12), not 44 as shown.

 

Best Wishes.

PeterClemmensen
Tourmaline | Level 20
data have;
input name $	string $	value;
datalines;
aba	aaaaa	12
baba	bbbbb	84
caca	cccc	65
gaga	ddddd	52
;

data want(drop=v);
   set have;
   if _N_=1 then v=value;
   diff=value-v;
   retain v;
run;

SAS Innovate 2025: Call for Content

Are you ready for the spotlight? We're accepting content ideas for SAS Innovate 2025 to be held May 6-9 in Orlando, FL. The call is open until September 25. Read more here about why you should contribute and what is in it for you!

Submit your idea!

Mastering the WHERE Clause in PROC SQL

SAS' Charu Shankar shares her PROC SQL expertise by showing you how to master the WHERE clause using real winter weather data.

Find more tutorials on the SAS Users YouTube channel.

Discussion stats
  • 5 replies
  • 986 views
  • 3 likes
  • 5 in conversation