Contributor
Posts: 39

# Finding observation and outputting that plus the row above and below

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;

Super User
Posts: 6,777

## Re: Finding observation and outputting that plus the row above and below

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.

Frequent Contributor
Posts: 77

## Re: Finding observation and outputting that plus the row above and below

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;

Discussion stats
• 2 replies
• 180 views
• 0 likes
• 3 in conversation