Reputation: 77
So I have a 20x20 matrix that is populated by zeroes. I have sampled this matrix and now have a vector with numbers from this sample. How do I get the coordinates of those sampled zeroes in the matrix?
a <- numeric(400)
mat <- matrix(a, 20, 20)
set.seed(1234)
sample_vector <- sample(mat, 6, replace=TRUE)
I've tried
which (mat ==0, arr.ind=TRUE)
but it returns the coordinates of all the zeroes in the matrix (unsurprisingly) and given that the matrix is populated only by zeroes, it won't return the coordinates of sampled zeroes.
How do I get those coordinates?
Upvotes: 1
Views: 109
Reputation: 73385
The problem is just like drawing 6 balls from a box of 400 white balls with replacement. Unless you label all 400 balls with unique numbers, they are identical and there is no way to know which have been drawn.
Similarly, now your matrix elements are labelled by (i,j)
. You may sample locations directly:
i <- sample(20, 6, TRUE)
j <- sample(20, 6, TRUE)
Then the elements being sampled are mat[cbind(i,j)]
.
Upvotes: 2
Reputation: 7190
you can just take into consideration that a matrix is just a vector with a dim
attributes in fact have that:
length(mat)
[1] 400
Knowing that, and that elements are stored columns wise, you can sample by using the length of the matrix:
set.seed(1234)
ind <- sample(length(mm), 10)
ind
[1] 12 62 60 61 83 97 1 22 99 47
and then subset:
mat[ind]
[1] 0 0 0 0 0 0 0 0 0 0
but you will now know that the first 0 is related to 12 which is the elements contained in element [2,2]
of the matrix, the second zero is contained in element [2,7]
, the third one [10, 6]
and so on.
Of course if the matrix would have, say 8 rows and 7 columns for example, and we would like to know the, say, 23th elements, divide 23 by 8, delete the integer part and multiply the number of rows by the decimal part:
((23 / 8))
[1] 2.875
8 * 0.875
[1] 7
the first two columns will be "full" so the 23th elements will be at the seventh place of the third column.
Upvotes: 0