SAS Programming

DATA Step, Macro, Functions and more
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 ;

sas-innovate-wordmark-2025-midnight.png

Register Today!

Join us for SAS Innovate 2025, our biggest and most exciting global event of the year, in Orlando, FL, from May 6-9. Sign up by March 14 for just $795.


Register now!

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