BookmarkSubscribeRSS Feed
noda6003
Quartz | Level 8

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

3 REPLIES 3
Kurt_Bremser
Super User
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.

andreas_lds
Jade | Level 19

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;
AllanBowe
Barite | Level 11

This macro can also be used to retrieve previous observations - https://core.sasjs.io/mp__prevobs_8sas.html

/Allan
SAS Challenges - SASensei
MacroCore library for app developers
SAS networking events (BeLux, Germany, UK&I)

Data Workflows, Data Contracts, Data Lineage, Drag & drop excel EUCs to SAS 9 & Viya - Data Controller
DevOps and AppDev on SAS 9 / Viya / Base SAS - SASjs

sas-innovate-2024.png

Available on demand!

Missed SAS Innovate Las Vegas? Watch all the action for free! View the keynotes, general sessions and 22 breakouts on demand.

 

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.

Click image to register for webinarClick image to register for webinar

Classroom Training Available!

Select SAS Training centers are offering in-person courses. View upcoming courses for:

View all other training opportunities.

Discussion stats
  • 3 replies
  • 382 views
  • 2 likes
  • 4 in conversation