How to identify coordinates in R

前端 未结 3 1461
[愿得一人]
[愿得一人] 2021-01-17 08:25

I would like to identify which coordinate of my vector gives me the greatest value. For a simple example suppose that:

x <- c(10,22,20,18,5)
3条回答
  •  伪装坚强ぢ
    2021-01-17 08:59

    Because you say co-ordinates, I am assuming the case-in-point may not always be a one-dimensional vector and therefore I am going to make my comment to @Jilber an answer.

    A general answer is to use which(x == max(x), ind.arr = TRUE). This will give you all dimensions of an array of any dimensionality. For e.g.

    R> x <- array(runif(8), dim=rep_len(2, 3))                                                                                                                              
    R> x
    , , 1
    
              [,1]      [,2]
    [1,] 0.3202624 0.7740697
    [2,] 0.9374742 0.2370483
    
    , , 2
    
              [,1]      [,2]
    [1,] 0.9423731 0.2099402
    [2,] 0.7035772 0.8195685
    
    R> which(x == max(x), arr.ind=TRUE)
         dim1 dim2 dim3
    [1,]    1    1    2
    
    R> which(x[1, , ] == max(x[1, , ]), arr.ind=TRUE)
         row col
    [1,]   1   2
    
    R> which(x[1, 1, ] == max(x[1, 1, ]), arr.ind=TRUE)
    [1] 2
    

    For the specific case of one-dimensional vectors, which.max is a 'faster' solution.

提交回复
热议问题