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 2025: Call for Content

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!

Submit your idea!

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.

Click image to register for webinarClick image to register for webinar

Classroom Training Available!

Select SAS Training centers are offering in-person courses. View upcoming courses for:

View all other training opportunities.

Discussion stats
  • 1 reply
  • 241 views
  • 0 likes
  • 2 in conversation