Hello,
I would like to have a value repeated until the next line is zero and if the next line is greater than zero then value be added to the previous value . here is a sample of my dataset and my desired output.
My data looks like this
id | date | gwil |
1 | 2014 | 0 |
1 | 2015 | 0 |
1 | 2016 | 100 |
1 | 2017 | 0 |
1 | 2018 | 0 |
1 | 2019 | 20 |
1 | 2020 | 0 |
1 | 2021 | 0 |
2 | 2015 | 0 |
2 | 2016 | 80 |
2 | 2017 | 0 |
2 | 2018 | 0 |
2 | 2019 | 15 |
2 | 2020 | 0 |
My desired output will look like this
id | date | gwill | gwill1 |
1 | 2014 | 0 | 0 |
1 | 2015 | 0 | 0 |
1 | 2016 | 100 | 100 |
1 | 2017 | 0 | 100 |
1 | 2018 | 0 | 100 |
1 | 2019 | 20 | 120 |
1 | 2020 | 0 | 120 |
1 | 2021 | 0 | 120 |
2 | 2015 | 0 | 0 |
2 | 2016 | 80 | 80 |
2 | 2017 | 0 | 80 |
2 | 2018 | 0 | 80 |
2 | 2019 | 15 | 95 |
2 | 2020 | 0 | 95 |
I used the following code and was able to repeat until the next value is zero but can't figure out how to add the next value for the rest of the obseravations.
data want; set have; by id notsorted; retain gwlim; if first.id or gwill > 0 then gwlim = gwill; rename gwlim = gwill1; run;
Any help is greatly appreciated!
For each ID, you apparently want GWILL1 to contain the running sum of all values of GWILL:
data want;
set have;
by id notsorted;
gwill1+gwill;
if first.id then gwill1=gwill;
run;
Untested, in the absence of a working DATA step with the sample data.
And slightly more compact, but a bit more obscure:
data want;
set have;
by id notsorted;
gwill2+ifn(first.id,gwill-gwill2,gwill);
run;
For each ID, you apparently want GWILL1 to contain the running sum of all values of GWILL:
data want;
set have;
by id notsorted;
gwill1+gwill;
if first.id then gwill1=gwill;
run;
Untested, in the absence of a working DATA step with the sample data.
And slightly more compact, but a bit more obscure:
data want;
set have;
by id notsorted;
gwill2+ifn(first.id,gwill-gwill2,gwill);
run;
try this code
proc sort data=have;
by id date;
run;
data want;
set have;
by id date;
retain gwill1;
if first.id then gwill1=0;
gwill1=gwill+gwill1;/* If you think of "add if greater equal to zero" as "always add," then you don't need the if statement. */
run;
Available on demand!
Missed SAS Innovate Las Vegas? Watch all the action for free! View the keynotes, general sessions and 22 breakouts on demand.
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.