How to identify coordinates in R

前端 未结 3 1462
[愿得一人]
[愿得一人] 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:47

    which.max is your friend as pointed out by @Hong Ooi

    > x <- c(10,22,20,18,5)
    > which.max(x)
    [1] 2
    

    Another (not optimal way) is a combination of which and max.

    > which(x==max(x))
    [1] 2
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2021-01-17 09:03

    First, find the greatest value with max:

    > max(x)
    [1] 22
    

    From there, you can figure out which value(s) in the vector match the greatest value:

    > x==max(x)
    [1] FALSE  TRUE FALSE FALSE FALSE
    

    which() can be used to translate the boolean vector into indices:

    which(x==max(x))
    [1] 2
    
    0 讨论(0)
提交回复
热议问题