R: How to rescale my matrix by column
I have a matrix of disease states states0CommercialA
, where the columns are states (i.e., "no disease", "disease", "dead") and the rows are model cycles (i.e., 1, 2, 3, 4, etc.).
I'm trying to multiply this by a vector of costs commercialMedExp
, wherein each cost corresponds to a disease state. I've attempted the following:
commercialMedExp * states0CommercialA
but it appears as though the multiplication is occurring across columns instead of across rows. Could someone help me with the correct syntax?
Column / Row rescaling is a common operation in matrix computation. You are looking for column rescaling, but I will offer solutions to both.
Row rescaling
A <- matrix(1:20, nrow = 5); x <- 1:5
## Any method below is much more efficient than `diag(x) %*% A`
## method 1: recycling
A * x
## method 2: `sweep()`
sweep(A, 1L, x, "*")
Column rescaling
A <- matrix(1:20, nrow = 5); y <- 1:4
## Any below method is much more efficient than `A %*% diag(y)`
## method 1: transpose + row rescaling
t(y * t(A))
## method 2: `sweep()`
sweep(A, 2L, y, "*")
## method 3: pairwise multiplication
A * rep(y, each = nrow(A))
What you can do
states0CommercialA * rep(commercialMedExp, each = nrow(states0CommercialA))