BookmarkSubscribeRSS Feed
☑ This topic is solved. Need further help from the community? Please sign in and ask a new question.
Mushy
Quartz | Level 8

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

1 ACCEPTED SOLUTION

Accepted Solutions
FreelanceReinh
Jade | Level 19

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).

View solution in original post

4 REPLIES 4
Mushy
Quartz | Level 8

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

FreelanceReinh
Jade | Level 19

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).

Mushy
Quartz | Level 8

@FreelanceReinh  Thanks for the solution 🙂

SAS Innovate 2025: Save the Date

 SAS Innovate 2025 is scheduled for May 6-9 in Orlando, FL. Sign up to be first to learn about the agenda and registration!

Save the date!

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
  • 4 replies
  • 859 views
  • 1 like
  • 3 in conversation