Taking first Differences

Accepted Solution Solved
Reply
Frequent Contributor
Posts: 122
Accepted Solution

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: 19,875

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;

View solution in original post


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

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;

Respected Advisor
Posts: 3,156

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
  • 315 views
  • 3 likes
  • 3 in conversation