BookmarkSubscribeRSS Feed
🔒 This topic is solved and locked. Need further help from the community? Please sign in and ask a new question.
hhchenfx
Rhodochrosite | Level 12

Hi,

My code below look back 3 row and count number of value positive.

It works quite fine except for the last rows of where the value is maxed at 4.

I try to do the "do n=_n_ to _n_+3 UNTIL eof" but fail.

Can you please help to fix it?

Thanks,

HHC

 

data h;
input Year_Month State $ Value;
datalines;
201401 CA -1
201402 CA .
201403 CA 2
201404 CA 5
201405 CA 8
201405 CA 2
201401 TX 1
201402 TX -4
201403 TX .
201404 TX 4
201405 TX 3
201405 TX 1
;


data w;
keep Year_Month state value c ;
set h nobs=totalobs;
c=0;
if value>0 then do;
	do n =_n_ to _n_+3;
		set h(rename =(Year_Month =ym state=st value=vl )) point=n;
		if st=state and vl>0 then c=c+1;
	end;
end;
run;

 

1 ACCEPTED SOLUTION

Accepted Solutions
Tom
Super User Tom
Super User

Your code appears to be looking ahead, not back.

You want to look at the current and three following observations?

do pointer=_n_ to min(_n_+3,totalobs);
  set h(....)  point=pointer;
  ...
end;

If you want to look back you could use LAG() function.  Or you could modify your DO loop.

do pointer=_n_ to max(_n_-3,1) by -1;
  set h(....)  point=pointer;
  ...
end;

 

View solution in original post

2 REPLIES 2
Tom
Super User Tom
Super User

Your code appears to be looking ahead, not back.

You want to look at the current and three following observations?

do pointer=_n_ to min(_n_+3,totalobs);
  set h(....)  point=pointer;
  ...
end;

If you want to look back you could use LAG() function.  Or you could modify your DO loop.

do pointer=_n_ to max(_n_-3,1) by -1;
  set h(....)  point=pointer;
  ...
end;

 

hhchenfx
Rhodochrosite | Level 12

Hi Tom,

Thanks for your comment.

I actually didn't know how to do look back and I got to do Sort before lol.

HHC

hackathon24-white-horiz.png

The 2025 SAS Hackathon has begun!

It's finally time to hack! Remember to visit the SAS Hacker's Hub regularly for news and updates.

Latest Updates

How to Concatenate Values

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.

SAS Training: Just a Click Away

 Ready to level-up your skills? Choose your own adventure.

Browse our catalog!

Discussion stats
  • 2 replies
  • 785 views
  • 3 likes
  • 2 in conversation