Extract position of values in a matrix in R

Asked

Viewed 44 times

1

I have the following data:

numbers <- c(303, 2107, 35000)
matriz <- matrix(1:90000, nrow = 300, ncol = 300, byrow=T)

I need the position of the values in the matrix. I am trying with the following code:

linha <- function(mat, vetor){
  aux <- which(apply(mat, 1, function(mat) all.equal(mat, vetor)) == "TRUE")
for (r in 1:nrow(matriz)) {  
    for (c in 1:ncol(matriz)) { 
       print(paste("Row", r, "and column",c, "have values of", matriz[r,c]))
  } }}

linha(matriz, numbers)

However, it is returning the position of all 90000 values.

Can anyone tell me where I’m going wrong? Or have another suggestion?

1 answer

4


I’m not sure what you want with the first line of your job, but check out the help for all.equal. Along with use of apply for the matrix lines, it probably isn’t doing what it expects. And anyway, the object aux is not being used later. What you have are two loops circulating through all rows and columns of the matrix, and this is what is being displayed.

To locate the index of a value in an array, you can use which with the option arr.ind = TRUE. For example:

which(matriz == 4, arr.ind = TRUE)
#>      row col
#> [1,]   1   4

You can use that inside a loop traverse all values of the number array:

linha <- function(mat, vetor) {
  for (valor in vetor) {
    rc <- which(mat == valor, arr.ind = TRUE)
    print(paste("Row", rc[1], "and column", rc[2], "have value of", valor))
  }
}

linha(matriz, numbers)
#> [1] "Row 2 and column 3 have value of 303"
#> [1] "Row 8 and column 7 have value of 2107"
#> [1] "Row 117 and column 200 have value of 35000"

If you need to store the result, you can use *apply instead of a loop and unite the result in a data frame.:

resultado <- as.data.frame(do.call("rbind", lapply(numbers, function(x) which(matriz == x, arr.ind = TRUE))))
resultado$value <- numbers

resultado
#>   row col value
#> 1   2   3   303
#> 2   8   7  2107
#> 3 117 200 35000
  • Thank you so much! Solved my question! D

Browser other questions tagged

You are not signed in. Login or sign up in order to post.