I have a dataset with 2 variables Amount and Balance. And I want to create a third variable balance_cf:
Amount Balance
109.98 85358.75
25.00 85358.75
-4500.00 85358.75
941.60 85358.75
104.00 85358.75
215.00 85358.75
110.00 85358.75
In the new dataset, Balance_cf will be equal to Balance for the first observation. For the second observation onwards, Balance_cf will be equal to its preceeding observation if amount>=0, else if amount<0, then balance_cf= lag(balance_cf)+amount.
The resultant dataset will look like this:
Amount Balance Balance_cf
109.98 85358.75 85358.75
25.00 85358.75 85358.75
-4500.00 85358.75 80858.75
941.60 85358.75 80858.75
104.00 85358.75 80858.75
215.00 85358.75 80858.75
110.00 85358.75 80858.75
47.72 85358.75 80858.75
-104.00 85358.75 80754.75
How do I achieve this? Thanks in advance for the help!
how about this code.
data have;
input Amount Balance;
datalines;
109.98 85358.75
25.00 85358.75
-4500.00 85358.75
941.60 85358.75
104.00 85358.75
215.00 85358.75
110.00 85358.75
47.72 85358.75
-104.00 85358.75
;
run;
data want;
set have;
retain Balance_cf;
if _n_=1 then Balance_cf = Balance;
else if amount<0 then balance_cf = balance_cf + amount;
run;
Build your skills. Make connections. Enjoy creative freedom. Maybe change the world. Registration is now open through August 30th. Visit the SAS Hackathon homepage.
Register today!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.
Select SAS Training centers are offering in-person courses. View upcoming courses for: