Use row and columns indices in matrix to extract values from matrix

前端 未结 1 1345

I have a Matrix A which looks like

A = matrix(1:9,3,3)
A
     [,1] [,2] [,3]
[1,]    1    4    7
[2,]    2    5    8
[3,]    3    6    9

and

1条回答
  •  隐瞒了意图╮
    2021-01-18 07:51

    From ?"[", you will find the following:

    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.

    and later on...

    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. Negative indices are not allowed in the index matrix. NA and zero values are allowed: rows of an index matrix containing a zero are ignored, whereas rows containing an NA produce an NA in the result.

    Thus, what you are looking for is simply:

    A[v]
    

    0 讨论(0)
提交回复
热议问题