Date: Wed, 3 Feb 2010 11:59:05 -0500
Reply-To: Arthur Tabachneck <art297@NETSCAPE.NET>
Sender: "SAS(r) Discussion" <SAS-L@LISTSERV.UGA.EDU>
From: Arthur Tabachneck <art297@NETSCAPE.NET>
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 #
> 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
|