mat  mat      [,1] [,2] [,3] [1,]    1..."/>
溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

R語言 選取某一行的最大值

發(fā)布時(shí)間:2020-06-27 10:43:15 來源:網(wǎng)絡(luò) 閱讀:12984 作者:qizok 欄目:編程語言

可以先自定義函數(shù),也可以用的時(shí)候再定義。


> 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"


另一個(gè)例子:

MaxVar <- function(x, na.rm = FALSE) {
  ## compute `max`
  maxx <- max(x, na.rm = na.rm)
  ## 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


參考: http://stackoverflow.com/questions/29683339/number-of-maximums-in-each-row-and-more/29686201#29686201


向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI