R: How to rescale my matrix by column

元气小坏坏 提交于 2019-11-27 02:18:59

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))
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!