Divide each data frame row by vector in R

前端 未结 5 792
逝去的感伤
逝去的感伤 2020-12-15 18:54

I\'m trying to divide each number within a data frame with 16 columns by a specific number for each column. The numbers are stored as a data frame with 1-16 corresponding to

5条回答
  •  温柔的废话
    2020-12-15 19:23

    This is nothing but element-wise matrix multiplication:

    mat <- matrix(c(4,2,2,6,7,6, 93,73,88,86,58,65, 123,103,96,128,46,57), nrow=3, byrow=T)
    
    vec = c(1.0660880,0.9104053,0.8642545,0.9611866,0.9711406,1.0560121)
    
    mat %o% 1/vec
    
               [,1]      [,2]       [,3]       [,4]      [,5]      [,6]
    [1,]   3.752035  2.080761   1.876018   6.242284  6.566062  6.242284
    [2,] 102.152305 75.169342  96.660246  88.555663 63.707889 66.931606
    [3,] 142.319190 97.536761 111.078392 121.210732 53.225063 53.976654
    

    To do that we used the outer-product approach, since directly trying mat %*% 1/vec gives an error on non-conformable arguments because they have different shapes. Or look at the many posts on https://stackoverflow.com/search?q=%5Br%5D+multiply+matrix+by+vector

提交回复
热议问题