CodeGuy - 1 month ago 6

R Question

I have a matrix in R that has

`N`

Specifically, I'd like to first identify all the rows that have the highest value (for that row) in column 1, and those should appear first in the matrix. Next, I'd like to identify all the rows that have the highest value in column 2 (for that row), and those should appear next in the matrix. And so on.

How can I do this?

Example case:

Let's say I have the matrix

`1 2 3 4 5 6`

3 5 4 4 3 5

7 1 2 3 2 4

Then the result of the sorting would place the first row at the end, because it's highest value is in the last column. It would place the 3rd row first, because it's higest value is in the first column. And it would place the middle row in between, because it's highest value is in the 2nd column.

Result:

`7 1 2 3 2 4`

3 5 4 4 3 5

1 2 3 4 5 6

Answer

Use `max.col`

and `order`

:

```
mat[ order(max.col(mat, "first")), ]
# [,1] [,2] [,3] [,4] [,5] [,6]
#[1,] 7 1 2 3 2 4
#[2,] 3 5 4 4 3 5
#[3,] 1 2 3 4 5 6
```

Where `mat`

was:

```
mat <- structure(c(1L, 3L, 7L, 2L, 5L, 1L, 3L, 4L, 2L, 4L, 4L, 3L, 5L,
3L, 2L, 6L, 5L, 4L), .Dim = c(3L, 6L))
```

It works because it calculates:

\1. Column position of the maximum value in each row:

```
max.col(mat, "first")
#[1] 6 2 1
```

\2. The order of rows based on these maximum values:

```
order(max.col(mat, "first"))
#[1] 3 2 1
```

Source (Stackoverflow)

Comments