I have a data set with variable a. I need to create variable b that is equal in line 1 to (1+a) and in each of the following lines to the value created for b in the previous line multiplied by (1+a) (a of the current line). I tried different things and each time run into another problem. The problem is how ot get the lag of variable b I just computed in the previous line. I tried using retain, and computing a lag variable outside the if statement, and it still does not work. For example:
data test2;
set test;
retain b;
lagb = lag(b);
if _N_ = 1 then b = sum(1,a);
else b= lagb * sum(1,a);
run;
Please provide example data and expected output for that data.
To continue with that approach you would need two datasteps, one to calculate the variable, the second to do the lag. You cannot use lag() and variables which are not fixed. There are other ways, such as retain, and merging on obs=obs+1. However without test data in the form of a datastep we cannot provide anything.
Thank you for your replys. I simplified the data. input data:
a
10
2
4
8
5
required output:
a b
10 11
2 33
4 165
8 1485
5 8910
As explained above, b is equal in line 1 to (1+a) and in each of the following lines to the value created for b in the previous line multiplied by (1+a) (a of the current line).
Thank you! Looks like the first code you wrote does the job.
I see what you did with the retain b and using that instead of lag.
Does the retaon 1 retain line 1?
Thank you again!
This statement:
retain b 1;
both retains B and gives it an initial value of 1 "Initial value" means at the very beginning of the DATA step, before reading in any of the data. It does NOT mean at the beginning of each observation.
Thank you for all your help!
SAS Innovate 2025 is scheduled for May 6-9 in Orlando, FL. Sign up to be first to learn about the agenda and registration!
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.
Ready to level-up your skills? Choose your own adventure.