4

I'm working in R and I'd like to call a selection of values from a data frame by their column and row indices. However doing this yields a matrix rather than an array. I shall demonstrate:

Given the 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 lets say I have two arrays pointing to the values I'd like to grab

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

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

a[ grab_row, grab_col ]

To get these results...

[1] 3 4 2

But that comes out as a 3x3 matrix, which makes enough sense in and of itself

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

Alright, I also see my answer is in the diagonal of the 3x3 matrix... but I'd really rather stick to an array as the output.

Any thoughts? Danka.

4

2 回答 2

4

Passing the row and column indices in as a two-column matrix (here constructed using cbind()) will get you the elements you were expecting:

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

This form of indexing is documented in ?"[":

Matrices and array:

[...snip...]

A third form of indexing is via a numeric matrix with the one column for each dimension: each row of the index matrix then selects a single element of the array, and the result is a vector.

于 2013-08-29T21:05:56.620 回答
1

Try this:

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

Works for both dataframes and matrices.

于 2013-08-29T21:03:47.857 回答