I want to extract data based on a string and also need one record above and one below.
Input data is like below
| S.No. | visit | value |
| 101 | V1 | 3 |
| 101 | V2 | 54 |
| 101 | Terminal | 566 |
| 101 | V3 | 67 |
| 102 | V1 | 88 |
| 102 | Terminal | 99 |
| 103 | V1 | 54 |
| 103 | V2 | 566 |
| 103 | V3 | 67 |
| 103 | Terminal | 22 |
| 103 | V4 |
11
|
Output should be like
| S.No. | visit | value |
| 101 | V2 | 54 |
| 101 | Terminal | 566 |
| 101 | V3 | 67 |
| 102 | V1 | 88 |
| 102 | Terminal | 99 |
| 103 | V3 | 67 |
| 103 | Terminal | 22 |
| 103 | V4 | 11 |
Can anyone please help me on how to get it
data want;
merge
have
have (
firstobs=2
keep=s_no visit
rename=(s_no=_sno visit = _visit)
)
;
if
visit = 'Terminal'
or
lag(s_no) = s_no and lag(visit) = 'Terminal'
or
_sno = s_no and _visit = 'Terminal'
;
run;
Untested; for tested code, supply example data in a working data step with valid (V7) SAS names.
Here is a solution using a hash-object:
data numbered;
set work.have;
pos = _n_;
run;
data want;
set work.numbered;
if _n_ = 1 then do;
declare hash h(dataset: 'work.numbered(where=(visit="Terminal"))');
h.defineKey('sno', 'pos');
h.defineDone();
end;
if visit = 'Terminal' or (h.check(key: sno, key: pos-1) = 0) or (h.check(key: sno, key: pos+1) = 0);
run;
This macro can also be used to retrieve previous observations - https://core.sasjs.io/mp__prevobs_8sas.html
April 27 – 30 | Gaylord Texan | Grapevine, Texas
Walk in ready to learn. Walk out ready to deliver. This is the data and AI conference you can't afford to miss.
Register now and lock in 2025 pricing—just $495!
Still thinking about your presentation idea? The submission deadline has been extended to Friday, Nov. 14, at 11:59 p.m. ET.
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.
Ready to level-up your skills? Choose your own adventure.