DiTe
DiTe

Reputation: 1

Use apply() in R to automate drawing specific row values from a matrix and do matrix operations

I have two matrices. Matrix A with variables x, y, a binary variable t1, and row numbers (row1, row2,....) that have values that correspond to rows in Matrix B. Matrix B has two columns with values that correspond to the x, y variables in Matrix A.

I want to multiply each row of matrix A with values drawn from matrix B for every value of row1 and row2, find the sum and multiply it with the row value from column t1 of matrix A.

Matrix A

x y t1 row1 row2
1 2 1 1 2
3 4 1 4 5
2 2 0 4 5

Matrix B

Rand_x Rand_y
0.01 0.252
0.78 -0.12
-0.77 0.004
-0.97 0.04
0.17 0.104

The row-wise operation would look something like this. The final output would be M, a 3x1 matrix.

([1 2] %% t([0.01 0.252]) + [1 2] %% t([0.78 -0.12]))*1 = 1.054

([3 4] %% t([-0.97 0.04]) + [1 2] %% t([0.17 0.104]))*1 = -0.512

([2 2] %% t([-0.97 0.04]) + [1 2] %% t([0.17 0.104]))*0 = 0

Matrix M

M
1.054
-0.512
0

I initially used for loops to loop over each matrix row and the values of row1, row 2, row 3..... Unfortunately for large matrices, computation time is in several minues (sometimes even hours). I would like to use apply() function to speed this.

What would be the most efficient way to do this?

I am new to R and stackoverflow. I apologize if my explanation was not clear.

Upvotes: 0

Views: 78

Answers (1)

Andrew Gustar
Andrew Gustar

Reputation: 18425

The figures in your example don't look right, so you might need to change it a bit, but here is how to do it (or at least something similar) with apply...

apply(mat_A, 1, function(x) (x[1:2] %*% mat_B[x[4],] +
                             x[1:2] %*% mat_B[x[5],]) * x[3])

[1]  1.054 -1.824  0.000

The function operates on each row of mat_A. Note that I think you want %*% for matrix multiplication, rather than %% for modulo, and to drop the t() transpose.

Upvotes: 2

Related Questions