Search code examples
rmatrixcellsample

Is there a way to do a random sample of a matrix to get cell location in R?


(I’m a beginner in R so sorry if this makes no sense)If I have a 3x3 matrix called M and I want to take a sample to get a random cell location, how would I do that? For example when I do sample(M,size=1,replace=FALSE) it gives me a random number from the matrix but I want it to give me the location of the number in the form of let’s say M[1,2] for example.


Solution

  • Suppose your matrix is like this:

    M <- matrix(1:9, 3)
    
    M
    #>      [,1] [,2] [,3]
    #> [1,]    1    4    7
    #> [2,]    2    5    8
    #> [3,]    3    6    9
    

    Then you can sample across rows and columns independently:

    set.seed(1)
    
    cell_index <- t(c(row = sample(nrow(M), 1), column = sample(ncol(M), 1)))
    
    cell_index
    #>      row column
    #> [1,]   1      3
    

    which allows

    M[cell_index]
    #> [1] 7
    

    Created on 2022-10-09 with reprex v2.0.2