Hi ,
I am trying to sum one variable as long as another remains constant. I want to cumulative sum dur as long as a is constant. when a changes the sum restarts. when a new id, the sum restarts.
id a dur
1 1 30
1 1 30
1 2 10
2 1 20
2 2 10
2 2 10
3 2 10
3 1 10
and I would like to do this:
id a dur sum
1 1 30 30
1 1 30 60
1 2 10 10
2 1 20 20
2 2 10 10
2 2 10 20
3 2 10 10
3 1 10 10
Thanks
@nataliavanessa0 wrote:
thank you @CarmineVerrell
But what if I don't want to combine all 1s and all 2s by ID, I just one to sum dur while a is constant but when it changes I want to restart the sum until it changes again?
something like this:
and I would like to do this:
id a dur sum
1 1 30 30
1 1 30 60
1 2 10 10
1 1 10 10
Thanks.
That would be the NOTSORTED option on the BY statement.
Data outdata; set indata; by notsorted id a; if first.a=1 then cumdur=0; cumdur+dur; run;
Notsorted aplies to all the the variables on the by statement regardless of the position it appears in the By statement.
You would need to sort your data and then use a data step.
Here is an example.
data indata;
infile cards;
input id a dur;
cards;
1 1 30
1 1 30
1 2 10
2 1 20
2 2 10
2 2 10
3 2 10
3 1 10
;
run;
Proc sort data=indata ;
by id a;
run;
Data outdata;
set indata;
by id a;
if first.a=1 then cumdur=0;
cumdur+dur;
if last.a;
run;
@nataliavanessa0 wrote:
thank you @CarmineVerrell
But what if I don't want to combine all 1s and all 2s by ID, I just one to sum dur while a is constant but when it changes I want to restart the sum until it changes again?
something like this:
and I would like to do this:
id a dur sum
1 1 30 30
1 1 30 60
1 2 10 10
1 1 10 10
Thanks.
That would be the NOTSORTED option on the BY statement.
Data outdata; set indata; by notsorted id a; if first.a=1 then cumdur=0; cumdur+dur; run;
Notsorted aplies to all the the variables on the by statement regardless of the position it appears in the By statement.
Are you ready for the spotlight? We're accepting content ideas for SAS Innovate 2025 to be held May 6-9 in Orlando, FL. The call is open until September 25. Read more here about why you should contribute and what is in it for you!
Learn how use the CAT functions in SAS to join values from multiple variables into a single value.
Find more tutorials on the SAS Users YouTube channel.