Given a matrix A
A <- matrix(1:8, nrow=2)
A
[,1] [,2] [,3] [,4]
[1,] 1 3 5 7
[2,] 2 4 6 8
I have a data frame indicating different coordinates
df <- data.frame(
INTr = c(2,2,1,2),
INTc = c(1,3,4,2)
)
and I have to evaluate a matrix A for each pair (INTc, INTr), i.e.
A[2,1]
A[2,3]
A[1,4]
A[2,2]
So far this is my code
D1 <- A[df$INTr, df$INTc] # Evaluate A for all the combinations
D2 <- diag(D1) # Keep only diagonal elements
Calculating D1 for big matrices is very memory expensive and cause R to crash.. Is there any way to get D2 without calculating D1?
Thanks