Solved
Contributor
Posts: 23

# How to find 3 largest values in a row

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!

Accepted Solutions
Solution
‎10-06-2015 03:49 PM
Valued Guide
Posts: 765

## Re: How to find 3 largest values in a row

[ Edited ]

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

All Replies
Solution
‎10-06-2015 03:49 PM
Valued Guide
Posts: 765

## Re: How to find 3 largest values in a row

[ Edited ]

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

Contributor
Posts: 23

## Re: How to find 3 largest values in a row

This is exactly what I needed. thank you!

🔒 This topic is solved and locked.