DATA Step, Macro, Functions and more

How to get the Value from the Previous Year

Reply
Contributor
Posts: 55

How to get the Value from the Previous Year

Hi,

I need help in creating the dataset, which gets the previous year value, or the base value when null.

data have;
input product $ scenario year value;
cards;
MOR 0 2016 800
MOR 0 2017 100
MOR 0 2018 0
MOR 0 2019 0
MOR 1 2017 0
MOR 1 2018 700
MOR 1 2019 600
;
run;

/*If it's Scenario 1, year 2017, and Value = 0, I should get the 2016 value of 800, functioning something like a base value*/
/*Else, I just get the value of the previous year*/

data want;
input product $ scenario year value;
cards;
MOR 0 2016 800
MOR 0 2017 100
MOR 0 2018 100
MOR 0 2019 100
MOR 1 2017 800
MOR 1 2018 700
MOR 1 2019 600
;
run;

Super User
Super User
Posts: 9,866

Re: How to get the Value from the Previous Year

Posted in reply to angeliquec

There are hundreds of examples on here of the use of lag() function and retained variables.  I personally prefer retained variables:

data want (drop=lstvalue);
  set have;
  retain lstval;
  lstval=ifn(value ne 0,value,lstval);
  if value=0 then value=lstvalue;
run;
Ask a Question
Discussion stats
  • 1 reply
  • 176 views
  • 0 likes
  • 2 in conversation