Solved
Contributor
Posts: 59

# Aggregate a variable across observations by group in cumulative fashion

Hello all,

I'm looking for code so that I can aggregate a variable across observations by group in a cumulative fashion... See below for desired result:

Unitid       TimePeriod    Variable    DesiredVariable

1                    1                  1                      1

1                    2                  0                      1

1                    3                  0                      1

1                    4                 2                       3

1                    5                  0                      3

2                   1                 0                       0

2                   2                 4                        4

2                   3                  0                      4

2                   4                1                        5

2                   5                 1                       6

If someone could help me out, then you guidance would be greatly appreciated!

Thank you,

Rich

Accepted Solutions
Solution
‎12-15-2017 10:28 AM
Posts: 2,836

## Re: Aggregate a variable across observations by group in cumulative fashion

Assuming the data is sorted by UnitId and TimePeriod

UNTESTED CODE

```data want;
set have;
by unitid;
if first.unitid then sum=0;
sum+variable;
run;```
--
Paige Miller

All Replies
Super User
Posts: 5,852

## Re: Aggregate a variable across observations by group in cumulative fashion

Accumulating data should only be done for reporting purposes. How will the users consume this data?
Data never sleeps
Posts: 2,836

## Re: Aggregate a variable across observations by group in cumulative fashion

LinusH wrote:
Accumulating data should only be done for reporting purposes.

I have never heard such a rule. And furthermore, it doesn't seem like a rule I would follow anyway. Could you please explain?

--
Paige Miller
Contributor
Posts: 59

## Re: Aggregate a variable across observations by group in cumulative fashion

Yeah, I don't believe such a rule exists either. But to let you in on my intent, it's to model the incrementally increasing threat posed by a particular effect across time. Thanks.
Solution
‎12-15-2017 10:28 AM
Posts: 2,836

## Re: Aggregate a variable across observations by group in cumulative fashion

Assuming the data is sorted by UnitId and TimePeriod

UNTESTED CODE

```data want;
set have;
by unitid;
if first.unitid then sum=0;
sum+variable;
run;```
--
Paige Miller
Contributor
Posts: 59