BookmarkSubscribeRSS Feed
🔒 This topic is solved and locked. Need further help from the community? Please sign in and ask a new question.
jlajla
Obsidian | Level 7

How do I find the 3 highest values for each observation across rows?

 

For instance:

ID X1 X2 X3 X4 X5

1   0    2   3   4   5  

2   0    0   1   2   3  

3   0    0   3   4   5 

 

The 3 largest for:

ID1=3,4,5

ID2=1,2,3

ID3= 3,4,5

 

I know this for the max value:

data MinMaxRows;
   set sashelp.Iris;
   array x {*} _numeric_;
   max = max(of x[*]);       
run;

 But how do I code for the three highest values?

Thank you!

1 ACCEPTED SOLUTION

Accepted Solutions
MikeZdeb
Rhodochrosite | Level 12

Hi, couple ideas (not sure if you want them as THREE TWO ONE or as ONE TWO THREE)  ...

 

data x;
input id x1-x5;
datalines;
1   0    2   3   4   5 
2   0    0   1   2   3 
3   0    0   3   4   5
;

 

data largest;
set x;
three = max(of x: );
two   = largest(2, of x: );
one   = largest(3,of x: );
run;

 

data largest;
array y(3) three two one;
set x;
do _n_=1 to 3;
   y(_n_) = largest(_n_, of x: );
end;
run;

 

both give ...

 

Obs    id    x1    x2    x3    x4    x5    three    two    one

 1      1     0     2     3     4     5      5       4      3
 2      2     0     0     1     2     3      3       2      1
 3      3     0     0     3     4     5      5       4      3

View solution in original post

2 REPLIES 2
MikeZdeb
Rhodochrosite | Level 12

Hi, couple ideas (not sure if you want them as THREE TWO ONE or as ONE TWO THREE)  ...

 

data x;
input id x1-x5;
datalines;
1   0    2   3   4   5 
2   0    0   1   2   3 
3   0    0   3   4   5
;

 

data largest;
set x;
three = max(of x: );
two   = largest(2, of x: );
one   = largest(3,of x: );
run;

 

data largest;
array y(3) three two one;
set x;
do _n_=1 to 3;
   y(_n_) = largest(_n_, of x: );
end;
run;

 

both give ...

 

Obs    id    x1    x2    x3    x4    x5    three    two    one

 1      1     0     2     3     4     5      5       4      3
 2      2     0     0     1     2     3      3       2      1
 3      3     0     0     3     4     5      5       4      3

jlajla
Obsidian | Level 7

This is exactly what I needed. thank you!

sas-innovate-white.png

Special offer for SAS Communities members

Save $250 on SAS Innovate and get a free advance copy of the new SAS For Dummies book! Use the code "SASforDummies" to register. Don't miss out, May 6-9, in Orlando, Florida.

 

View the full agenda.

Register now!

What is Bayesian Analysis?

Learn the difference between classical and Bayesian statistical approaches and see a few PROC examples to perform Bayesian analysis in this video.

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
  • 2744 views
  • 0 likes
  • 2 in conversation