- Mark as New
- Bookmark
- Subscribe
- Mute
- RSS Feed
- Permalink
- Report Inappropriate Content
Posted 05-04-2022 12:13 PM
(312 views)
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.
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
- Mark as New
- Bookmark
- Subscribe
- Mute
- RSS Feed
- Permalink
- Report Inappropriate Content
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 ;