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

Hi,

suppose I have the following data:

periodvalue
110
25
3
412

I would like to add a column of returns, so for example the return for period 2 = (5-10)/10 = -0.5 

For period 3 I don't have a value, so in this case the return for period 3 = "missing", and for period 4, its return should be (12-5)/5 = 1.4, that is, 5 is the value from period 2 because its the nearest period for which there is a value.

Thank you!

1 ACCEPTED SOLUTION

Accepted Solutions
Haikuo
Onyx | Level 15

data have;

     infile cards truncover;

     input period    value;

     cards;

1 10

2 5

3

4 12

;

data want;

     set have;

     retain temp;

     return=ifn(temp=., ., (value-temp)/temp);

     temp=coalesce(value, temp);

     drop temp;

run;


Update:

In SAS there ALMOST certain will be more than one solutions. So below is another one using Proc SQL, but not recommended for efficiency reason:

proc sql;

  create table want as

  select *, value/(select value from have where period < a.period and not missing(value) having period=max(period))-1 as return

  from have a;

quit;

View solution in original post

2 REPLIES 2
Haikuo
Onyx | Level 15

data have;

     infile cards truncover;

     input period    value;

     cards;

1 10

2 5

3

4 12

;

data want;

     set have;

     retain temp;

     return=ifn(temp=., ., (value-temp)/temp);

     temp=coalesce(value, temp);

     drop temp;

run;


Update:

In SAS there ALMOST certain will be more than one solutions. So below is another one using Proc SQL, but not recommended for efficiency reason:

proc sql;

  create table want as

  select *, value/(select value from have where period < a.period and not missing(value) having period=max(period))-1 as return

  from have a;

quit;

naveen_srini
Quartz | Level 8

data have;

     infile cards truncover;

     input period    value;

     cards;
1 10
2 5
3
4 12
;

data want;
set have;
retain value1;
if value ne . then do;
value1=value;
return=(value-lag(value1))/lag(value1);
end;
drop value1;
run;

SAS Innovate 2025: Register Now

Registration is now open for SAS Innovate 2025 , our biggest and most exciting global event of the year! Join us in Orlando, FL, May 6-9.
Sign up by Dec. 31 to get the 2024 rate of just $495.
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
  • 1291 views
  • 3 likes
  • 3 in conversation