Contributor
Posts: 38

# How to average up several rows of different group with condition

I've come across this problem that I want to average up rows that have exact same OrganizationID, Product and ProductLine, make it one row, with summed numerator as new numerator, summed denominator as new denominator, and summed numerator/summed denominator as new rate(AggregareRate).

The average up will only happen if all three column values are the same(OrganizationID, Product and ProductLine). So in the example below, when either product or productline have different values under same organizationID, the rows stay the way it is - only red rows got averaged up.

Here is the input data:

 OrganizationID Product ProductLine numerator denominator rate 1 Shoes Commercial 50 200 0.25 1 Shoes Commercial 60 120 0.5 1 Shoes Non-Commercial 30 50 0.6 2 Shoes Commercial 80 160 0.5 2 Shoes Non-Commericial 90 180 0.5 2 Cloth Commercial 70 100 0.7 2 Cloth Commercial 60 300 0.2

The desired output should look like:

 OrganizationID Product ProductLine numerator denominator AggregateRate 1 Shoes Commercial 110 320 0.34375 1 Shoes Non-Commercial 30 50 0.6 2 Shoes Commercial 80 160 0.5 2 Shoes Non-Commericial 90 180 0.5 2 Cloth Commercial 130 400 0.325

Thank you!

Posts: 5,626

## Re: How to average up several rows of different group with condition

What have you tried so far?

PG
Super User
Posts: 24,025

## Re: How to average up several rows of different group with condition

[ Edited ]

PROC MEANS, SQL, SUMMARY, UNIVARIATE, or DATA STEP.

Check the PROC MEANS examples for one related to your question.

https://github.com/statgeek/SAS-Tutorials/blob/master/proc_means_basic

If youre having difficulties with a specific issue from here post your code and log.

Posts: 1,848

## Re: How to average up several rows of different group with condition

There are many tools to reach the desired output, as @Reeza mentiond.

You can do it in one step (datastep) or in two steps (proc means or proc summary + datastep).

Attached is the code for one datastep, assuming data is already sorted

BY OrganizationID Product and ProductLine;

``````data want;
set have;
by OrganizationID Product ProductLine;
retain sum_num sum_denom;
if first.ProductLine then do;
sum_num = nemurator;
sum_denom = denominator;
end; else do;
sum_num =sum(sum_num nemurator);
sum_denom = sum(sum_denom denominator);
end;

if last.ProductLine then do;
AggregateRate = sum_num / sum_denom;
output;
end;      format AggregateRate 8.5;  /* or any other preffered format */
run;

``````
Contributor
Posts: 38

## Re: How to average up several rows of different group with condition

This is great, thank you.
Contributor
Posts: 38

## Re: How to average up several rows of different group with condition

Thank you for this!
Discussion stats
• 5 replies
• 151 views
• 0 likes
• 4 in conversation