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;

hackathon24-white-horiz.png

The 2025 SAS Hackathon Kicks Off on June 11!

Watch the live Hackathon Kickoff to get all the essential information about the SAS Hackathon—including how to join, how to participate, and expert tips for success.

YouTube LinkedIn

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.

SAS Training: Just a Click Away

 Ready to level-up your skills? Choose your own adventure.

Browse our catalog!

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