How do I loop an operation over a matrix?

Viewed 43
A <- matrix(1:50, nrow = 5)   #a matrix
B <- matrix(3:7, nrow = 5)  #another matrix
C <- matrix(data = NA, nrow = nrow(A), ncol = ncol(A))

I want to divide each cell in each row A by the single cell in each row B and I want the result to be stored in C. I have tried using for loop but I don't know how to do that.

4 Answers

R is a vectorized language. You can divide matirix A column-wise by B (which is effectively a vector since it's a 7x1 matrix). The function we need for this is apply, where we choose MARGIN=2 for column-wise. The preparation of an empty matrix C is also not needed.

C <- apply(A, 2, `/`, B)
C
#           [,1]     [,2]     [,3]     [,4]     [,5]     [,6]      [,7]
# [1,] 0.3333333 2.000000 3.666667 5.333333 7.000000 8.666667 10.333333
# [2,] 0.5000000 1.750000 3.000000 4.250000 5.500000 6.750000  8.000000
# [3,] 0.6000000 1.600000 2.600000 3.600000 4.600000 5.600000  6.600000
# [4,] 0.6666667 1.500000 2.333333 3.166667 4.000000 4.833333  5.666667
# [5,] 0.7142857 1.428571 2.142857 2.857143 3.571429 4.285714  5.000000
#           [,8]      [,9]     [,10]
# [1,] 12.000000 13.666667 15.333333
# [2,]  9.250000 10.500000 11.750000
# [3,]  7.600000  8.600000  9.600000
# [4,]  6.500000  7.333333  8.166667
# [5,]  5.714286  6.428571  7.142857

Is this what you are looking for?

A <- matrix(1:50, nrow = 5)   #a matrix
B <- matrix(3:7, nrow = 5)  #another matrix
C <- matrix(NA, nrow = nrow(A), ncol = ncol(A))


for(i in 1:nrow(A)){
   C[i,] <- A[i,]/B[i,1]
}

Two alternatives:

C <- A / B[, rep(1, ncol(A))]

C <- t(sapply(seq_len(NROW(A)), function(i) A[i, ] / B[i]))

And two more using similar logic to jay.sf:

C <- sapply(seq_len(NCOL(A)), function(i) A[, i] / B)

for (i in seq_len(NCOL(A)))  C[, i] <- A[, i] / B

Or you can (ab)use R ability to recycle arguments and define B as a vector :

A <- matrix(1:50, nrow = 5)   #a matrix
B <- 3:7
A/B
#>           [,1]     [,2]     [,3]     [,4]     [,5]     [,6]      [,7]      [,8]
#> [1,] 0.3333333 2.000000 3.666667 5.333333 7.000000 8.666667 10.333333 12.000000
#> [2,] 0.5000000 1.750000 3.000000 4.250000 5.500000 6.750000  8.000000  9.250000
#> [3,] 0.6000000 1.600000 2.600000 3.600000 4.600000 5.600000  6.600000  7.600000
#> [4,] 0.6666667 1.500000 2.333333 3.166667 4.000000 4.833333  5.666667  6.500000
#> [5,] 0.7142857 1.428571 2.142857 2.857143 3.571429 4.285714  5.000000  5.714286
#>           [,9]     [,10]
#> [1,] 13.666667 15.333333
#> [2,] 10.500000 11.750000
#> [3,]  8.600000  9.600000
#> [4,]  7.333333  8.166667
#> [5,]  6.428571  7.142857
Related