BookmarkSubscribeRSS Feed
Shradha1
Obsidian | Level 7

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!

1 REPLY 1
japelin
Rhodochrosite | Level 12

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;

Ready to join fellow brilliant minds for the SAS Hackathon?

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!
How to Concatenate Values

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.

Click image to register for webinarClick image to register for webinar

Classroom Training Available!

Select SAS Training centers are offering in-person courses. View upcoming courses for:

View all other training opportunities.

Discussion stats
  • 1 reply
  • 347 views
  • 1 like
  • 2 in conversation