BookmarkSubscribeRSS Feed
ari
Quartz | Level 8 ari
Quartz | Level 8

I have dataset with multiple observations per subject.

 

Have:

IDtv
1302.95
1225.11
1232.33
1214.3
1282.28

 

I want to create a dataset to keep only one record per subject where the  variable 't' closest to value 24.

want:  
IDtv
1232.33

 

Any help to do this in sas?

 

Thanks

 

6 REPLIES 6
RW9
Diamond | Level 26 RW9
Diamond | Level 26

Simplest way I can think of is to create an offset var, then sort by offset and take n=1:

data want;
  set have;
  offset=ifn(t<24,24-t,t-24);
run;
proc sort data=want;
  by offset;
run;
data want;
  set want (obs=1);
run;

Not tested as not typing in test data - post as a datastep next time.

ari
Quartz | Level 8 ari
Quartz | Level 8
Thanks RW9
Patrick
Opal | Level 21

or this way:

data have;
input ID t v;
datalines;
1 30 2.95
1 22 5.11
1 23 2.33
1 21 4.3
1 28 2.28
;
run;

proc sql;
  create table want as
    select id, t, v 
    from have
    group by id
    having min(abs(24-t))=abs(24-t)
    ;
quit;
ari
Quartz | Level 8 ari
Quartz | Level 8
Thanks Patrick
Kurt_Bremser
Super User

Since you indicate there are multiple IDs:

data int;
set have;
offset = abs(t-24);
run;

proc sort data=int;
by id offset;
run;

data want;
set int;
by id;
if first.id;
drop offset;
run;

For larger datasets, this might be more performant than doing it with SQL.

ari
Quartz | Level 8 ari
Quartz | Level 8
Thanks Kurt

sas-innovate-2024.png

Join us for SAS Innovate April 16-19 at the Aria in Las Vegas. Bring the team and save big with our group pricing for a limited time only.

Pre-conference courses and tutorials are filling up fast and are always a sellout. Register today to reserve your seat.

 

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
  • 6 replies
  • 937 views
  • 0 likes
  • 4 in conversation