Hi everyone,
I have a sasdataset that looks like this. I need to recalculate the total column using values from the previous month and ratio from the current month. I tried using lag and retain function but I couldn’t get the correct answer. Any suggestion?
SAS dataset;
data t1;
input group $ amt ratio month total;
datalines;
A 1200 0.2 1 240
B 3290 0.1 2 0
C 2000 0.1 3 0
A 1000 0.4 1 240
B 5000 0.5 2 0
C 1430 0.6 3 0
;
run;
data t2;
set t1;
if month gt 2 then do;
total = ratio * lag(total);
end;
retain total;
run;
desire results:
A 1200 0.2 1 240
B 3290 0.1 2 24
C 2000 0.1 3 2.4
A 1000 0.4 1 240
B 5000 0.5 2 120
C 1430 0.6 3 72
Here's a way that should work:
data t2;
prior_total = total;
set t1;
if month > 1 then total = ratio * prior_total;
run;
A couple of notes ... you used gt as the comparison. But the results are consistent with ge, not gt (hence month > 1 in my code). Also, there is no need to retain TOTAL. Since it is part of an incoming SAS data set, it is automatically retained. It's up to you if you want to drop PRIOR_TOTAL. You might want to keep it the first time, to better understand how the program works.
Looking at your desired data output, I'm guessing that this has to happen only for Group B and C and not when the group is equal to A?
You can't calculate LAG conditionally.
Calculate lag outside of the IF condition and then you can use it in the IF condition.
Here's a way that should work:
data t2;
prior_total = total;
set t1;
if month > 1 then total = ratio * prior_total;
run;
A couple of notes ... you used gt as the comparison. But the results are consistent with ge, not gt (hence month > 1 in my code). Also, there is no need to retain TOTAL. Since it is part of an incoming SAS data set, it is automatically retained. It's up to you if you want to drop PRIOR_TOTAL. You might want to keep it the first time, to better understand how the program works.
data t1;
input group $ amt ratio month total;
datalines;
A 1200 0.2 1 240
B 3290 0.1 2 0
C 2000 0.1 3 0
A 1000 0.4 1 240
B 5000 0.5 2 0
C 1430 0.6 3 0
;
run;
data t2;
set t1_NEW;
FORMAT NEWTOTAL 8.2;
retain NEWTOTAL;
IF MONTH = 1 THEN DO;
NEWTOTAL = TOTAL;
END;
if month GE 2 then do;
NEWTOTAL = ratio * NEWTOTAL;
end;
run;
Edit: Sorry, forgot the final run command!
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.
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.