可以先自定义函数,也可以用的时候再定义。


> 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]})   # 查找每一列
[1] 2 2 2

> apply(mat, 1, function(x){order(x, decreasing=T)[1]})   # 查找每一行
[1] 3 3 3
> apply(mat, 1, function(x){which.max(x)})                # 查找每一行
[1] 3 3 3


> n <- letters[1:5]
> n
[1] "a" "b" "c" "d" "e"

> t <- apply(mat, 1, function(x){which.max(x)})
> n[t]
[1] "c" "c" "c"


另一个例子:

MaxVar <- function(x, na.rm = FALSE) {
  ## compute `max`
  maxx <- max(x, na.rm &