Solved
Contributor
Posts: 21

# How to get a value from this year minus last year.

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,

Accepted Solutions
Solution
‎02-24-2017 05:26 PM
Super User
Posts: 6,774

## Re: How to get a value from this year minus last year.

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.

All Replies
Frequent Contributor
Posts: 75

## Re: How to get a value from this year minus last year.

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.

Super User
Posts: 9,599

## Re: How to get a value from this year minus last year.

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.

Contributor
Posts: 21

Thank you!

PROC Star
Posts: 8,164

## Re: How to get a value from this year minus last year.

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

Solution
‎02-24-2017 05:26 PM
Super User
Posts: 6,774

## Re: How to get a value from this year minus last year.

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.

☑ This topic is solved.