根据列向量对矩阵进行子集 [英] Subset a matrix according to a columns vector
问题描述
我有一个矩阵H.我想从每一行中选择一个值,然后从向量P中选择列.
I have a matrix, H. I want to select a value from each row, choosing the column from vector P.
H = matrix(data=runif(6),ncol=2)
P = c(2,1,2)
我追求的输出是包含的向量
The output I am after is a vector containing
c(H[1,P[1]],H[2,P[2]],H[3,P[3]])
我正在处理较大的数据,所以一般的方法会很好.
I'm working with larger data, so a generic way of doing this would be good.
这对diag(H[,P])
有效,但是:a)我不明白为什么H[,P]
返回平方矩阵,并且b)我宁愿不使用额外的功能(在这种情况下为diag
).
This works diag(H[,P])
, but: a) I don't understand why H[,P]
returns a square matrix, and b) I would rather not use an extra function (in this case diag
).
很抱歉,如果以前曾问过这个问题.
My apologies if this has been asked before.
推荐答案
尝试
H[cbind(seq_len(nrow(H)), P)]
## [1] 0.6733731 0.7396847 0.5953580
在这里,我们按P
关于您的问题,所以H[, P]
返回矩阵的原因是因为您告诉R:
Regarding your question, so the reason H[, P]
returns a matrix is because you are telling R:
从矩阵"H"中选择第2、1、2列中的所有行
select all rows in columns: 2, 1, 2 from matrix "H"
因此您得到的结果是一个具有相同的第一列和第三列的矩阵.
thus the result that you are getting is a matrix with identical first and third columns.
这篇关于根据列向量对矩阵进行子集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!