Recall multiple values ​​from row and column data in R

I work in R and I would like to call a selection of values ​​from a data frame by their columns and row indices. However, this results in a matrix, not an array. I will demonstrate:

Given data.frame:

a = data.frame( a = array(c(1,2,3,4,5,6,7,8,9), c(3,3)) ) 

(for those of you who don't want to plug it in, it looks like this)

  a.1 a.2 a.3 1 1 4 7 2 2 5 8 3 3 6 9 

And let's say I have two arrays pointing to the values ​​I would like to capture

 grab_row = c(3,1,2) grab_col = c(1,2,1) 

Now I expect this to be the code I want ...

 a[ grab_row, grab_col ] 

To get these results ...

 [1] 3 4 2 

But it comes out as a 3x3 matrix, which in itself has sufficient meaning

  a.1 a.2 a.1.1 3 3 6 3 1 1 4 1 2 2 5 2 

Ok, I also see that my answer is on the diagonal of a 3x3 matrix ... but I really would prefer to use an array as output.

Any thoughts? Danka.

+4
source share
2 answers

Passing row and column indices as a two-column matrix (built here using cbind() ) will bring you the elements you expect:

 a[cbind(grab_row, grab_col)] [1] 3 4 2 

?"[" this form of indexing documented in ?"[" :

Matrices and Array:

[... chick ...]

The third form of indexing is through a numerical matrix with one column for each dimension: each row of the index matrix, then selects one element of the array, and the result is a vector.

+4
source

Try the following:

 > mapply(function(i,j)a[i,j], grab_row, grab_col) [1] 3 4 2 

Works for both data and matrices.

+1
source

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


All Articles