Indexing a multidimensional table using a column vector

I have contingency tables of different sizes. I would 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] ?

+6
source share
2 answers

In response to @ttmaccer answer: does this work because of a (slightly) obscure paragraph in ?"[" , Which 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)] 

consists in converting ii to a 1x4 matrix, which [ interprets as a matrix as described above; a[matrix(ii,nrow=1)] will be more explicit, but less compact.

The good thing about this approach (besides avoiding the magically 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 
+3
source

If I understand your question correctly, this construct, using do.call() , should do what you want:

 ## Create an example array and a variable containing the desired index a <- array(1:1e4, dim = c(10, 10, 10, 10)) ii <- c(5, 5, 5, 5) ## Use do.call to extract the desired element. do.call("[", c(list(a), ii)) # [1] 4445 

The call above works because all equivalents are:

 a[5, 5, 5, 5] `[`(a, 5, 5, 5, 5) do.call("[", list(a, 5, 5, 5, 5)) do.call("[", c(list(a), ii)) 
+2
source

Source: https://habr.com/ru/post/920737/


All Articles