简体   繁体   中英

Evaluate diagonal elements in a matrix R

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), ie

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

OK, it seems like you really just want

D2 <- A[cbind(df$INTr, df$INTc)]

(no need to create D1 ). Note that indexing with a matrix like this allows you to specify a different column for each row.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM