I have a matrix which I want to convert to one with binary output (0 vs 1). The matrix to be converted contains four rows of rankings (1 to 4):
mat1.data <- c(4, 3, 3, 3, 3, 2, 2, 1, 1, 1,
3, 4, 2, 4, 2, 3, 1, 3, 3, 2,
2, 2, 4, 1, 1, 1, 4, 4, 2, 4,
1, 1, 1, 2, 4, 4, 3, 2, 4, 3)
mat1 <- matrix(mat1.data,nrow=4,ncol=10,byrow=TRUE)
mat1
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
[1,] 4 3 3 3 3 2 2 1 1 1
[2,] 3 4 2 4 2 3 1 3 3 2
[3,] 2 2 4 1 1 1 4 4 2 4
[4,] 1 1 1 2 4 4 3 2 4 3
For each row in the input matrix, I want to create four binary rows - one row for each value of the ranks (1-4). In the binary matrix, each row-wise entry is 1 on positions where the focal rank occurs in the input matrix, and 0 otherwise. Each row from the original matrix should produce 10*4=40 entries in the output matrix.
For example, for the first row of in the input matrix...
4 3 3 3 3 2 2 1 1 1
...the output should be:
0 0 0 0 0 0 0 1 1 1 # Rank 1 in input
0 0 0 0 0 1 1 0 0 0 # Rank 2 in input
0 1 1 1 1 0 0 0 0 0 # Rank 3 in input
1 0 0 0 0 0 0 0 0 0 # Rank 4 in input
Continue with this process, the expected output for all four rows of rankings should look like this:
0 0 0 0 0 0 0 1 1 1 #first row of rankings starts
0 0 0 0 0 1 1 0 0 0
0 1 1 1 1 0 0 0 0 0
1 0 0 0 0 0 0 0 0 0 #first row of rankings ends
0 0 0 0 0 0 1 0 0 0 #second row of rankings starts
0 0 1 0 1 0 0 0 0 1
1 0 0 0 0 1 0 1 1 0
0 1 0 1 0 0 0 0 0 0 #second row of rankings ends
0 0 0 1 1 1 0 0 0 0 #third row of rankings starts
1 1 0 0 0 0 0 0 1 0
0 0 0 0 0 0 0 0 0 0
0 0 1 0 0 0 1 1 0 1 #third row of rankings ends
1 1 1 0 0 0 0 0 0 0 #fourth row of rankings starts
0 0 0 1 0 0 0 1 0 0
0 0 0 0 0 0 1 0 0 1
0 0 0 0 1 1 0 0 1 0 #fourth row of rankings ends
How do I do achieve this? I have a larger dataset and so a more efficient method is preferred but any help will be greatly appreciated!
rowsum(1:4 * m, rep(1:4, each=4))
, wherem
is the binary matrix output (and change4
to generalise the number of ranks) – Tugglemat <- matrix(which(m == 1) %% 4, 4); mat[mat == 0] <- 4
. – Mosesmatrix( (which(m == 1) - 1) %% 4 + 1 , 4)
) – Tuggle-1
then+1
shift. Your solutions are great. Perhaps OP can post this as a second question (well, it is) and you answer it! – Moses