BookmarkSubscribeRSS Feed
laneylaners
Obsidian | Level 7

Lets say I have the following dataset work.train_test:

 

Time Channel Distance
11 1 24
12 1 26
13 1 28
14 2 40
15 2 42
16 3 44

 

and i want to 'find' variable time when it equals 13, and then output that row plus the one above and one below it, so that a new dataset work.train_time is below:

 

 

Time Channel Distance
12 1 26
13 1 28
14 2 40

 

 

 

how would i go about doing this?  do i need to use a counter?  in my actual data, i know the value i want, but i do not know the time values of the ones above or below (so i cannot use a 'between' statement).

 

data work.train_time;

set work.train_test;

where time = 13;

(statement to output row above and below the row that outputs time = 13)

run;

 

 

 

 

 

2 REPLIES 2
Astounding
PROC Star

Here's one way (untested):

 

data want;

set have nobs=_total_obs_;

if time=13;

output;

previous = _n_ -1;

next = _n_ + 1;

if (1 <= previous <= _total_obs_) then do;

   set have point=previous;

   output;

end;

if (1 <= next <= _total_obs_) then do;

   set have point=next;

   output;

end;

run;

 

Depending on the placement of the 13s, you might end up outputting the same observation twice.  For example, the same record might be the next record after a 13, and might also be the previous record before the following 13.  If you think that might be an issue we can code around it.

 

Good luck.

MadhuKorni
Quartz | Level 8


data have;
input Time Channel Distance;
cnt+1;
if time = 13 then
do;
call symput('obs1',cnt-1);
call symput('obs2',cnt);
call symput('obs3',cnt+1);
end;
cards;
11 1 24
12 1 26
13 1 28
14 2 40
15 2 42
16 3 44
;

data want(drop = cnt);
set have;
if cnt in (&obs1 &obs2 &obs3);
run;

hackathon24-white-horiz.png

2025 SAS Hackathon: There is still time!

Good news: We've extended SAS Hackathon registration until Sept. 12, so you still have time to be part of our biggest event yet – our five-year anniversary!

Register Now

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
  • 1255 views
  • 0 likes
  • 3 in conversation