# [R] how to divide each element of a matrix by a specific value per column

Marc Schwartz marc_schwartz at me.com
Thu Jan 27 16:44:11 CET 2011

```On Jan 27, 2011, at 9:18 AM, adam_pgsql wrote:

>
> Hi,
>
> I'd like to divide each element of a matrix by a specific value per column. These specific values are stored in a list. For example:
>
>> x <- c(1,2,3,4,5)
>> y <- matrix(c(1:30), nrow = 6)
>
> Now I want to divide each element in y[,1] by x[1], y[,2] by x[2] etc. I have tried this
>
>> my_function <- function(data, ind) data/ind
>> apply(y, 2, my_function, x)
>     [,1] [,2] [,3] [,4] [,5]
> [1,]    1  7.0 13.0 19.0 25.0
> [2,]    1  4.0  7.0 10.0 13.0
> [3,]    1  3.0  5.0  7.0  9.0
> [4,]    1  2.5  4.0  5.5  7.0
> [5,]    1  2.2  3.4  4.6  5.8
> [6,]    6 12.0 18.0 24.0 30.0
> Warning messages:
> 1: In data/ind :
>  longer object length is not a multiple of shorter object length
> 2: In data/ind :
>  longer object length is not a multiple of shorter object length
> 3: In data/ind :
>  longer object length is not a multiple of shorter object length
> 4: In data/ind :
>  longer object length is not a multiple of shorter object length
> 5: In data/ind :
>  longer object length is not a multiple of shorter object length
>
> but as you can see it is applying them by row rather than column. Any ideas how to do this? Is there a variable within 'apply' that can be used to determine which column of y is being processed?
>
> thanks for any help
>

Here is one approach:

> t(t(y) / x)
[,1] [,2]     [,3] [,4] [,5]
[1,]    1  3.5 4.333333 4.75  5.0
[2,]    2  4.0 4.666667 5.00  5.2
[3,]    3  4.5 5.000000 5.25  5.4
[4,]    4  5.0 5.333333 5.50  5.6
[5,]    5  5.5 5.666667 5.75  5.8
[6,]    6  6.0 6.000000 6.00  6.0

You essentially transpose the 'y' matrix so that the normal vector cycling of 'x' is applied properly, then transpose the result back to the original orientation.

HTH,

Marc Schwartz

```