0

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

MrFlick
  • 195,160
  • 17
  • 277
  • 295
user3036416
  • 1,205
  • 2
  • 15
  • 28
  • 1
    What do you mean by "evaluate a matrix A"? You should include a [complete, reproducible example](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) so we can see exactly what your code is doing. Like what is matrix A? You may wish to make a smaller example to make it easier to reproduce. – MrFlick Jul 28 '14 at 16:41
  • This still isn't complete or runnable. How many rows does `df` have? What is the shape of `D1`? – MrFlick Jul 28 '14 at 16:53

1 Answers1

1

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.

MrFlick
  • 195,160
  • 17
  • 277
  • 295