Date: Wed, 3 Feb 2010 11:19:21 -0600 "Feyerharm, Robert W." "SAS(r) Discussion" "Feyerharm, Robert W." Re: lag calculation macro To: Arthur Tabachneck <201002031659.o13GaGqa005735@malibu.cc.uga.edu> TEXT/plain; charset="us-ascii"

Perfect, works like a charm!

Thanks Arthur!

-----Original Message----- From: Arthur Tabachneck [mailto:art297@NETSCAPE.NET] Sent: Wednesday, February 03, 2010 10:59 AM To: SAS-L@LISTSERV.UGA.EDU; Feyerharm, Robert W. Subject: Re: lag calculation macro

Robert,

Retain might be more appropriate here. How about something like:

data test (drop=lastx); input x y; retain lastx; if not(missing(x)) then lastx=x; if missing(x) then x=lastx; datalines; 1 1 . 2 . 3 . 4 . 5 2 6 . 7 . 8 3 9 . 10 . 11 . 12 . 13 . 14 ;

HTH, Art -------- On Wed, 3 Feb 2010 11:47:37 -0500, Robert Feyerharm <robertf@HEALTH.OK.GOV> wrote:

>Has anyone else struggled with the lag function in SAS? The lag function >often doesn't work in an intuitive manner in conditional statements, or if >missing values are involved. > >Anyways, I wrote a short macro code to handle lag calculations which I'd >like to share. It works fairly well, although I may be reinventing the >wheel. A colleague was working with a large dataset containing missing >values, and wanted to impute the last known value into the missing values >for a particular field. For example, given the following test dataset, the >macro fills in the missing values of x with the last known value of x >(1,2, or 3): > >data test; >input x y; >datalines; >1 1 >. 2 >. 3 >. 4 >. 5 >2 6 >. 7 >. 8 >3 9 >. 10 >. 11 >. 12 >. 13 >. 14 >; >run; > >/* Let num = no. of records in target dataset. */ >%let num=14; > >%macro lagvar(num); >%do i = 1 %to &num; > data test; > set test; > z=lag(x); > if x=. then x=z; > run; >%end; > >data test; >set test; > drop z; >run; >%mend; > >%lagvar(&num) > >I'm curious if there is a shorter program that can handle the same >operations without resorting to a macro? > >Robert Feyerharm >Oklahoma State Department of Health

Back to: Top of message | Previous page | Main SAS-L page