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]
?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With