Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Indexing multidimensional table using column vector

Tags:

r

I have contingency tables of varying sizes. I'd like to index them using a set of values from a dataset. However, myTable[c(5,5,5,5)] clearly does not do what I want. How do I get c(5,5,5,5) to read as myTable[5,5,5,5]?

like image 631
dave Avatar asked Jul 17 '12 20:07

dave


1 Answers

Following up on @ttmaccer's answer: this works because of the (slightly) obscure paragraph in ?"[" that reads:

When indexing arrays by ‘[’ a single argument ‘i’ can be a
matrix with as many columns as there are dimensions of ‘x’;
the result is then a vector with elements corresponding to
the sets of indices in each row of ‘i’.

The effect of using t(ii) in

ii <- c(5,5,5,5)
a[t(ii)]

is to convert ii to a 1x4 matrix that [ interprets as a matrix as described above; a[matrix(ii,nrow=1)] would be more explicit but less compact.

The nice thing about this approach (besides avoiding the magical-seeming aspects of do.call) is that it works in parallel for more than one set of indices, as in

jj <- matrix(c(5,5,5,5,
               6,6,6,6),byrow=TRUE,nrow=2)
a[jj]
## [1] 4445 5556
like image 123
Ben Bolker Avatar answered Oct 13 '22 05:10

Ben Bolker