SoFunction
Updated on 2025-04-10

R language to select the maximum value of a certain row

You can customize the functions first

It can also be defined when used.

> mat <- matrix(c(1:3,7:9,4:6), byrow = T, nc = 3)
> mat
     [,1] [,2] [,3]
[1,]    1    2    3
[2,]    7    8    9
[3,]    4    5    6 
 
> apply(mat, 2, function(x){order(x, decreasing=T)[1]})   # Find each column[1] 2 2 2
 
> apply(mat, 1, function(x){order(x, decreasing=T)[1]})   # Find each line[1] 3 3 3
> apply(mat, 1, function(x){(x)})                # Find each line[1] 3 3 3 
 
> n <- letters[1:5]
> n
[1] "a" "b" "c" "d" "e"
 
> t <- apply(mat, 1, function(x){(x)})
> n[t]
[1] "c" "c" "c"

Another example:

MaxVar <- function(x,  = FALSE) {
  ## compute `max`
  maxx <- max(x,  = )
  ## which equal the max
  wmax <- which(x == max(x))
  ## how many equal the max
  nmax <- length(wmax)
  ## return
  out <- if(nmax > 1L) {
    c(999, NA)
  } else {
    c(maxx, wmax)
  }
  out
} 
 
And use it like this:
 
> new <- apply(Mydata[, -1], 1, MaxVar)
> new
     [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
[1,]    3    4  999  999  999    4    4    2    4   999
[2,]    1    4   NA   NA   NA    4    2    3    4    NA
 
> Mydata <- cbind(Mydata, Max = new[1, ], Var = new[2, ])
> Mydata
   ID X1 X2 X3 X4 Max Var
1   1  3  1  1  1   3   1
2   2  1  2  1  4   4   4
3   3  1  1  1  1 999  NA
4   4  1  3  3  1 999  NA
5   5  2  2  2  1 999  NA
6   6  1  2  3  4   4   4
7   7  2  4  3  3   4   2
8   8  1  1  2  1   2   3
9   9  3  2  1  4   4   4
10 10  4  4  4  4 999  NA

Supplement: Use R language to obtain the subscript of all maximum or minimum values ​​in a vector

For example, vector a:

a=c(1,2,4,3,4)

The code is as follows:

which(a==max(a),=TRUE)

The output is:

[1] 3 5

The above is personal experience. I hope you can give you a reference and I hope you can support me more. If there are any mistakes or no complete considerations, I would like to give you advice.