I have a data set that calculates trade deficit in various years. I need to calculate the trade deficit between the last year of the data set and the second to last year of the data set. Please advise,
So that's really all that is involved? No third variable like COUNTRY? If you are only concerned with that single difference, here is a way to add it onto the final observation:
proc sort data=have;
by year;
run;
data want;
set have end=done;
deficit_diff = diff(deficit);
if done=0 then deficit_diff=.;
run;
This program calculates the deficit difference on every pair of observations, then wipes out the calculated value for all but the final pair of years.
Please provide a sample of the dataset preferably in data step code form that we can run. generate and then try out a solution for you.
YRDIFF() function can get years between 2 dates. If you want good answers then provide the required information, we can't see anything about what your tring to do, so post test data in the form of a datastep and required output and any other information.
Thank you!
If you just need to calculate the change (delta) of the most recent two years of your data per company, then you could use something like:
data have; set sashelp.class (rename=(sex=company height=deficit weight=year)); run; proc sort data=have; by company descending year; run; data want (keep=company delta); set have; by company; retain hold_deficit; if first.company then do; counter=1; hold_deficit=deficit; end; else do; counter+1; if counter eq 2 then do; delta=hold_deficit/deficit-1; output; end; end; run;
Art, CEO, AnalystFinder.com
So that's really all that is involved? No third variable like COUNTRY? If you are only concerned with that single difference, here is a way to add it onto the final observation:
proc sort data=have;
by year;
run;
data want;
set have end=done;
deficit_diff = diff(deficit);
if done=0 then deficit_diff=.;
run;
This program calculates the deficit difference on every pair of observations, then wipes out the calculated value for all but the final pair of years.
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!
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.
Ready to level-up your skills? Choose your own adventure.