## How to count means of consecutive values in sas?

Solved
Occasional Contributor
Posts: 11

# How to count means of consecutive values in sas?

I have a data with for example:

Year Age Value

1          1     y1

2          1     y2

3          1     y3

1          2     y4

2          2     y5

3          2     y6

How can I count values into a new dataset with:

Year Age Value

1          1     (y1+y2)/2

2          1     (y2+y3)/2

3          1     y3

1          2     (y4+y5)/2

2          2     (y5+y6)/2

3          2     y6

That is to say, I want means of consecutive years in each age. Last years may say as they are.

Accepted Solutions
Solution
‎01-17-2014 06:06 AM
Frequent Contributor
Posts: 106

## Re: How to count means of consecutive values in sas?

data test;

input Year Age Value;

obs=_N_;

cards;

1 1 1

2 1 2

3 1 3

1 2 4

2 2 5

3 2 6

;run;

proc sort data=test;by descending obs;run;

data test ;

set test;

retain final_value 0;

by  descending age  ;

if first.age then final_value=value;

else final_value=(final_value+value)/2;output;final_value=value;

if last.age then final_value=(final_value+value)/2;

run;

proc sort data=test out=test(drop=obs);by obs;run;

All Replies
Super User
Posts: 5,876

## Re: How to count means of consecutive values in sas?

Use the data step using SET BY, combined with RETAIN and/or first. and last. logic.

Data never sleeps
Occasional Contributor
Posts: 11

## Re: How to count means of consecutive values in sas?

Can you give me an example code?

Super User
Posts: 5,876

## Re: How to count means of consecutive values in sas?

Please, there is an excelent search function on support.sas.com:

"data set by retain first last", in Sample & SAS Notes.

Data never sleeps
Solution
‎01-17-2014 06:06 AM
Frequent Contributor
Posts: 106

## Re: How to count means of consecutive values in sas?

data test;

input Year Age Value;

obs=_N_;

cards;

1 1 1

2 1 2

3 1 3

1 2 4

2 2 5

3 2 6

;run;

proc sort data=test;by descending obs;run;

data test ;

set test;

retain final_value 0;

by  descending age  ;

if first.age then final_value=value;

else final_value=(final_value+value)/2;output;final_value=value;

if last.age then final_value=(final_value+value)/2;

run;

proc sort data=test out=test(drop=obs);by obs;run;

🔒 This topic is solved and locked.