DATA Step, Macro, Functions and more

Calculate difference between first and last observation

Accepted Solution Solved
Reply
New Contributor
Posts: 2
Accepted Solution

Calculate difference between first and last observation

I have the following dataset

 

data have;
input profit;
datalines;
52
34

60

57

70
;
run;

 

I want to write a program that will create a new dataset, only containing the difference between the first and last observation?

In this case the code would show 70 (last observation) - 52 (first observation), so the output would be 18.

 

 


Accepted Solutions
Solution
‎04-09-2017 01:16 PM
PROC Star
Posts: 7,360

Re: Calculate difference between first and last observation

Here is one way:

 

data want;
  set have end=last;
  retain first;
  if _n_ eq 1 then first=profit;
  if last then do;
    result=profit-first;
    output;
  end;
run;

Art, CEO, AnalystFinder.com

 

View solution in original post


All Replies
Solution
‎04-09-2017 01:16 PM
PROC Star
Posts: 7,360

Re: Calculate difference between first and last observation

Here is one way:

 

data want;
  set have end=last;
  retain first;
  if _n_ eq 1 then first=profit;
  if last then do;
    result=profit-first;
    output;
  end;
run;

Art, CEO, AnalystFinder.com

 

PROC Star
Posts: 166

Re: Calculate difference between first and last observation

hi,


data want(drop=_profit);
set have(firstobs=min);
set have(rename=(profit=_profit)) nobs=_nobs_ point=_nobs_;
d=_profit-profit;
output;
stop;
run;

 

Regards,

Naveen Srinivasan

☑ This topic is SOLVED.

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

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