Hi All,
Following is the data set:
id marks1 marks2
1 10 20
1 30 30
1 20 40
1 20 40
2 20 10
2 100 90
2 30 20
2 20 40
Expected result : I would like to know how we could calculate the final variable using only LAG function?
id | marks1 | marks2 | final | |
1 | 10 | 20 | 10 | if first.id then MARKS1 |
1 | 30 | 30 | 40 | if not first.id then lag(final)+marks2 |
1 | 20 | 40 | 80 | |
1 | 20 | 40 | 120 | |
2 | 20 | 10 | 20 | |
2 | 100 | 90 | 110 | |
2 | 30 | 20 | 130 | |
2 | 20 | 40 | 170 |
Thanks and Regards,
Mushy
Hi @Mushy,
@Mushy wrote:
I would like to know how we could calculate the final variable using only LAG function?
Here's how:
data want(drop=lf);
set have;
by id;
if first.id then final=marks1;
else do;
link op_q; /* retrieve previous FINAL from the queue */
final=lf+marks2;
end;
op_q: lf=lag(final); /* operate the queue */
run;
As you can see, a computed value can be saved in a LAG queue for the next iteration of the DATA step, but it's easier to use a retained variable for this purpose (as Kurt_Bremser has suggested).
No LAG needed, just a retained variable:
data want;
set have;
by id;
if first.id
then final = marks1;
else final + marks2;
run;
Hello Kurt,
Thanks for the response. Indeed I know this solution. But I want to know how a LAG could be applied on the calculated value.
Thanks in advance ,
Mushy
Hi @Mushy,
@Mushy wrote:
I would like to know how we could calculate the final variable using only LAG function?
Here's how:
data want(drop=lf);
set have;
by id;
if first.id then final=marks1;
else do;
link op_q; /* retrieve previous FINAL from the queue */
final=lf+marks2;
end;
op_q: lf=lag(final); /* operate the queue */
run;
As you can see, a computed value can be saved in a LAG queue for the next iteration of the DATA step, but it's easier to use a retained variable for this purpose (as Kurt_Bremser has suggested).
@FreelanceReinh Thanks for the solution 🙂
Are you ready for the spotlight? We're accepting content ideas for SAS Innovate 2025 to be held May 6-9 in Orlando, FL. The call is open until September 25. Read more here about why you should contribute and what is in it for you!
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.