Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dividing columns of a matrix by elements of a vector [duplicate]

Tags:

r

I am figuring out how to divide the nth column of a matrix by the nth element of a row vector.

For example, let matrix a and vector b be:

a <- matrix(1:9, byrow = TRUE,  nrow = 3)
b <- c(3:5)

giving

[[1]]
     [,1] [,2] [,3]
[1,]    1    2    3
[2,]    4    5    6
[3,]    7    8    9

[[2]]
[1] 3 4 5

In this case, I'm looking for code that divides the first column of the matrix by 3, second by 4 and the thrird by 5.

I have tried using the apply function with no success

c <- apply(a, 2, function(x) x / b)

Is there any code that can do this with apply and preferably without using loops?

like image 452
Adrian Avatar asked Jan 08 '18 13:01

Adrian


1 Answers

You could use sweep for this:

#same as apply the second argument needs to be 1 for row or 2 for column
sweep(a, 2, b, FUN = '/')
#          [,1] [,2] [,3]
#[1,] 0.3333333 0.50  0.6
#[2,] 1.3333333 1.25  1.2
#[3,] 2.3333333 2.00  1.8
like image 56
LyzandeR Avatar answered Sep 19 '22 03:09

LyzandeR