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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With