Given a 5x5 matrix:
dataset=matrix(cbind(c(1,1,2,2,0),
c(1,1,2,0,0),
c(0,0,0,1,0),
c(0,0,1,1,1),
c(1,2,3,4,0))
dataset
[,1] [,2] [,3] [,4] [,5]
[1,] 1 1 0 0 1
[2,] 1 1 0 0 2
[3,] 2 2 0 1 3
[4,] 2 0 1 1 4
[5,] 0 0 0 1 0
I want to sample 1 observation from each row of the matrix where the value to be sampled from the row is equal to 1 and I want to create a new matrix that the randomly sampled value is set to True
in the new matrix and all other values are set to false
. A sample of the expected output is provided below:
1 2 3 4 5
1 FALSE TRUE FALSE FALSE FALSE
2 TRUE FALSE FALSE FALSE FALSE
3 FALSE FALSE FALSE TRUE FALSE
4 FALSE FALSE TRUE FALSE FALSE
5 FALSE FALSE FALSE TRUE FALSE
Could someone please help me to figure out how I can achieve this.
matrix(
doesn't make sense. Just usecbind()
– John Coleman