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;
Don't miss out on SAS Innovate - Register now for the FREE Livestream!
Can't make it to Vegas? No problem! Watch our general sessions LIVE or on-demand starting April 17th. Hear from SAS execs, best-selling author Adam Grant, Hot Ones host Sean Evans, top tech journalist Kara Swisher, AI expert Cassie Kozyrkov, and the mind-blowing dance crew iLuminate! Plus, get access to over 20 breakout sessions.
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.