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?
Something like
commercialMedExp0A <- t(apply(states0CommercialA, 1, function(x){ x * commercialMedExp}))
should work so long as the number of columns in states0CommericialA
is the same length as commercialMedExp
. If it is not you would have to subset the data. For example, if the disease states are in columns 13 through 18
commercialMedExp0A <- t(apply(states0CommercialA[,c(13:18)], 1, function(x){ x * commercialMedExp}))
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))
来源:https://stackoverflow.com/questions/38977872/r-how-to-rescale-my-matrix-by-column