Search code examples
rmatrixna

Processing the matrix data by using which(), and return all the row names


I would like to process the following matrix data by using which(), and return all the row names, for example:

m = matrix(seq(-1,1, 0.5), nrow = 3)

#     [,1] [,2]
#[1,] -1.0  0.5
#[2,] -0.5  1.0
#[3,]  0.0 -1.0

which(m==0.5,arr.ind=TRUE)
#       row col
# [1,]   1   2

How can I get the matrix like this? All row names can be shown in the table, and the missing value in col is NA.

#       row col
# [1,]   1   2
# [2,]   2   NA
# [3,]   3   NA
# [4,]   4   NA  

Solution

  • Here is a method that first change the matrix into a dataframe, and use tidyr::complete() to "expand" the dataframe based on the number of rows of m. Finally change it back to a matrix.

    library(tidyverse)
    
    as.data.frame(which(m==0.5,arr.ind=TRUE)) %>% 
      complete(row = 1:nrow(m)) %>% 
      as.matrix()
    
        row col
    [1,]   1   2
    [2,]   2  NA
    [3,]   3  NA