## Taking first Differences

Solved
Frequent Contributor
Posts: 126

# Taking first Differences

To whom it may concern,

I have a dataset that looks like this and I need to take the first difference of the variable balance. So far, I have used a dif function, but my problem is that everytime that ABA changes, I need to reset the diff so that the first record of a new aba is not subtracted from the last records of the preceeding aba. This is not a simle dif that I can apply to the entire of the balance column; I give some illustration of the problem below as well.

Any takers?

ABA    Minute  Balance  First Difference

123       21:01   435            435

123       21:02   436              1

123       21:03   437              1

456       20:01   567              0  If I use a dif function, this result turns into 130 and I do not wat that.

457       20:02   568              1

458      20:03    569              1

Accepted Solutions
Solution
‎11-13-2012 05:53 PM
Super User
Posts: 24,016

## Re: Taking first Differences

Posted in reply to maroulator

Add in by groups.

data want;

set have;

by aba;

first_difference=dif(balance);

if first.aba then first_difference=0;

run;

All Replies
Solution
‎11-13-2012 05:53 PM
Super User
Posts: 24,016

## Re: Taking first Differences

Posted in reply to maroulator

Add in by groups.

data want;

set have;

by aba;

first_difference=dif(balance);

if first.aba then first_difference=0;

run;

Posts: 3,186

## Re: Taking first Differences

Posted in reply to maroulator

By your definition, I suppose you have some typos in your raw data , ABA since after 456 should be staying the same, instead of 457,458. Fareeza's solution is dead on, here is just some different dressing:

data want;

set have;

by aba;

first_difference=ifn(first.aba,0,dif(balance));

run;

Haikuo

🔒 This topic is solved and locked.

Need further help from the community? Please ask a new question.

Discussion stats
• 2 replies
• 444 views
• 3 likes
• 3 in conversation