使用向量中的索引从矩阵中提取元素 [英] Use indices in vector to extract elements from matrix

查看:116
本文介绍了使用向量中的索引从矩阵中提取元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个看起来像的矩阵A

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 a vector of indices of elements I am interested in:

v=matrix(c(1, 3, 2, 2, 2, 3),3,2)
v
     [,1] [,2]
[1,]    1    2
[2,]    3    2
[3,]    2    3

v中的行和列索引对应于数字4 = A [1,2],6和8.

The rows and column indices in v correspond to the numbers 4 = A[1,2], 6 and 8.

如何在不使用循环的情况下直接从A中提取这些数字?

How can I extract those numbers directly from A without using a loop?

当我使用

A[v[,1],v[,2]]

我知道

     [,1] [,2] [,3]
[1,]    4    4    7
[2,]    6    6    9
[3,]    5    5    8

因为R接受v的第一列和第二列的所有组合.

because R takes all combinations of the first and second column of v.

我想要的是一个可以直接给我4,6,8的表达式.

What I want is an expression which gives me directly 4,6,8.

我可以采用对角线元素,但是必须有一种更简单的方法.

I could just take the diagonal elements but there must be an easier way.

推荐答案

?"["中,您将找到以下内容:

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

当用[单个参数索引数组时,我可以是矩阵,其列数与x的维数一样多;结果是一个向量,该向量的元素与i的每一行中的索引集相对应.

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.

以后……

索引的第三种形式是通过一个数字矩阵,每个维都有一列:索引矩阵的每一行然后选择数组的单个元素,结果是一个向量.索引矩阵中不允许使用负索引.允许使用NA和零值:索引矩阵中包含零的行将被忽略,而包含NA的行将在结果中产生NA.

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]

这篇关于使用向量中的索引从矩阵中提取元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆