BookmarkSubscribeRSS Feed
atnk
Fluorite | Level 6
Hi: In the data set below, I want to sum the current record plus the last 2 records to create the var (sumlast3). The var hit is equal to 1 if sumlast3 equals 3. I used the lag in the following way but it is not working:
Sumlast3=lag(target)+lag2(target)+lag3(target);
Data Have

obs target
a 1
a 0
a 1
a 1
a 1
a 1
b 0
b 1
b 1
b 1
b 1

Data Want:

obs target sumlast3 hit
a 1
a 0
a 1 2 0
a 1 2 0
a 1 3 1
a 1 3 1
b 0
b 1
b 1 2 0
b 1 3 1
b 1 3 1

Thanks.
1 REPLY 1
AMSAS
SAS Super FREQ

Try this

data have ;
	infile cards ;
	input ob $ target ;
cards ;
a 1
a 0
a 1
a 1
a 1
a 1
b 0
b 1
b 1
b 1
b 1
;
run ;

proc sort in=have out=srtd ;
	by ob ;
run ;

data want ;
	retain target_1 target_2 ;
	set have ;
	by ob ;
	if first.ob then do ;
		target_1=0 ;
		target_2=0 ;
	end ;
	sumlast3=sum(target,target_1,target_2) ;
	if sumlast3=3 then hit=1 else hit=0 ;
	target_2=target_1 ;
	target_1=target ;
	output ;
run ;

hackathon24-white-horiz.png

The 2025 SAS Hackathon has begun!

It's finally time to hack! Remember to visit the SAS Hacker's Hub regularly for news and updates.

Latest Updates

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
  • 540 views
  • 0 likes
  • 2 in conversation