I am building a longitudial data for my study. The input data has id, year, event, and event year variables. I am trying to create a variable z which is time elapsed from the last event. Can someone show a data step that computes z? Thanks.
id year event event_yr z
1 1986 0 .
1 1987 0 .
1 1988 0 .
1 1989 0 .
1 1990 0 .
1 1991 0 .
1 1992 0 .
1 1993 0 .
1 1994 0 .
1 1995 0 .
1 1996 1 1996
1 1997 0 .
1 1998 0 .
1 1999 0 .
1 2000 0 .
1 2001 1 2001 5
1 2002 0 .
1 2003 0 .
1 2004 0 .
1 2005 0 .
1 2006 0 .
1 2007 0 .
1 2008 1 2008 7
1 2009 0 .
1 2010 0 .
1 2011 0 .
1 2012 0 .
1 2012 0 .
2 2010 0 .
2 2011 1 2011 0
2 2012 0 .
3 2007 0 .
3 2008 1 2008 0
3 2009 1 2009 1
3 2010 0 .
3 2011 0 .
3 2012 1 2012 3
: Assuming your data are already sorted like in your example, and that you really want to assign a 0 for id eq 1 and event_yr eq 1996, then something like the following should suffice:
data want;
set have;
by id;
retain last_event;
if first.id then call missing(last_event);
if event eq 1 then do;
z=ifn(last_event gt 0,event_yr-last_event, 0);
last_event=event_yr;
end;
run;
: Assuming your data are already sorted like in your example, and that you really want to assign a 0 for id eq 1 and event_yr eq 1996, then something like the following should suffice:
data want;
set have;
by id;
retain last_event;
if first.id then call missing(last_event);
if event eq 1 then do;
z=ifn(last_event gt 0,event_yr-last_event, 0);
last_event=event_yr;
end;
run;
Available on demand!
Missed SAS Innovate Las Vegas? Watch all the action for free! View the keynotes, general sessions and 22 breakouts on demand.
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.