Search code examples
rmatrixscale

Dividing a matrix by a vector with ncol=number of matrix columns


I have a dilemma in using R.

data1

    [A] [B] [C]
[a]  2   3   5
[b]  3   2   4

data2

[c]  4   3   5

result

    [A] [B] [C]
[a]  .5  1   1
[b] .75 .67 .8

here's the thing. I would like every values per column in data1 to be divided by corresponding value in data2, like divide column A by 4, column B by 3. I would like to have a result with a structure identical to data1. Can you help me?


Solution

  • This is a job for sweep:

    sweep(data1, 2, data2, FUN="/")
    
         [,1]      [,2] [,3]
    [1,] 0.50 1.0000000  1.0
    [2,] 0.75 0.6666667  0.8
    

    Or:

    t(t(data1)/c(data2))