Search code examples
rindexingdata.tablematrix-indexing

Taking a data.table slice with a sequence of (row,col) indices


I have a data.table that resembles the one below.

tab <- data.table(a = c(NA, 42190, NA), b = c(42190, 42190, NA), c = c(40570, 42190, NA))
tab
       a     b     c
1:    NA 42190 40570
2: 42190 42190 42190
3:    NA    NA    NA

Upon specification of a vector of row indices, and a vector of column indices, I would like a vector returned containing the points in tab corresponding to the specified vector of row indices and column indices.

For example, suppose I wanted to get the diagonal elements in tab. I would specify two vectors,

ri <- 1:3
ci <- 1:3

and some function, function(ri, ci, tab), would return the diagonal elements of tab.

If tab were a data.frame, I would do what's below,

as.data.frame(tab)[cbind(ri, ci)]

but, I would like to avoid data.frame syntax. I would also like to avoid a for loop, as this tends to be slow.


Solution

  • There is a faster way to do this than coercing to either matrix or data.frame. Just use the [data.frame function.

    `[.data.frame`( tab,  cbind(ri,ci) )
    [1]    NA 42190    NA
    

    This is the functional syntax for the [.data.frame function.