I have a bunch of transition matrices that look like these.
> temp
31-60 5-30 61-90 Current PaidOff
5-30 283 317 9 500 9
Current 0 2935 0 179989 1689
PaidOff 0 0 0 0 0
I want to standardize the size so I've made a 0 matrix with the correct row and column names:
> blankMatrix
Current 5-30 31-60 61-90 91-120 ChargeOff_Default PaidOff
Current 0 0 0 0 0 0 0
5-30 0 0 0 0 0 0 0
31-60 0 0 0 0 0 0 0
61-90 0 0 0 0 0 0 0
91-120 0 0 0 0 0 0 0
ChargeOff_Default 0 0 0 0 0 0 0
PaidOff 0 0 0 0 0 0 0
Is there a way to easily add the first matrix to the second. So for instance the number 283 would go into position (2,3) automatically. I'm hoping to avoid a long and messy for loop where I constantly iterate and check if the row and column names match.
Thank you!
You can create a matrix of row and column index from the row and column names of temp using expand.grid and then blankMatrix[matrix index] will select values from the index pair in the matrix index; To change the values at the corresponding index, just assign the values to it;
temp <- as.matrix(temp)
blankMatrix <- as.matrix(blankMatrix)
matIndex <- as.matrix(expand.grid(rownames(temp), colnames(temp)))
blankMatrix[matIndex] <- temp
blankMatrix
# Current X5.30 X31.60 X61.90 X91.120 ChargeOff_Default PaidOff
#Current 179989 2935 0 0 0 0 1689
#5-30 500 317 283 9 0 0 9
#31-60 0 0 0 0 0 0 0
#61-90 0 0 0 0 0 0 0
#91-120 0 0 0 0 0 0 0
#ChargeOff_Default 0 0 0 0 0 0 0
#PaidOff 0 0 0 0 0 0 0
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With