Betty
Betty

Reputation: 37

How do I keep only the last 10 observations in SAS once an if condition is met?

How can I modify the below code to tell SAS that if trend is UP or Down then keep the last 10 observations in the dataset? The below code only keeps that particular observation, but I need to see the 10 observations before that, too. Thanks!

Data want;
set have;
if TrendDown=1 and ck1=1 and ck2=1 then Trend='Down';
if TrendUp=1 and ck1=1 and ck2=1 then Trend='Up';
if Trend='Up' or Trend='Down';
run;

Upvotes: 0

Views: 606

Answers (1)

Longfish
Longfish

Reputation: 7602

The following code does what you're asking, taking advantage of the current row number and the POINT statement to read the previous 9 rows and the current row. I've also asked it to set the current value of the Trend variable to all 10 rows, using the RETAIN statement. Hope this helps.

Data want;
set have;
if TrendDown=1 and ck1=1 and ck2=1 then Trend='Down';
if TrendUp=1 and ck1=1 and ck2=1 then Trend='Up';
if Trend in ('Up','Down') then do i = -9 to 0;
    obnum = _n_+i;
    set have point=obnum;
    retain Trend;
    drop i;
    output;
    end;
run;

Upvotes: 1

Related Questions