如何将指标上的所有元素都存储在向量中?

时间:2022-10-06 04:15:36

I have a matrix where every row consists of zeros and a single one, say y <- rbind(c(1,0,0), c(0,1,0), c(0,1,0)) and I have a vector holding indices for each row, say x <- c(1,2,3) and . Now I would like to count the number of times that y[i,x[i]] == 1 holds. I know I could do this like

我有一个矩阵,其中每一行由0和一个单列组成,比如y <- rbind(c(1,0,0), c(0,1,0), c(0,1,0))我有一个向量保持每一行的指标,比如x <- c(1,2,3)和。现在我想计算y[I,x[I] == 1的次数。我知道我可以这样做

count <- 0
for(i in 1:3)
    count <- count + y[i, x[i]]

but I was interested if there would be a smarter way. Something like count <- sum(y[,x]). Of course this does not work, because y[,x] gives a matrix.

但如果有更聪明的方法,我很感兴趣。比如count <- sum(y[,x])当然这个不行,因为y[x]给出了一个矩阵。

Therefore my question is there a way to get a vector with the elements at the positions given by another vector by using apply or any other smart trick, i.e. without for-loops?

因此,我的问题是,是否有一种方法,可以通过应用或任何其他巧妙的技巧,即不使用for循环,来得到一个向量在另一个向量给定的位置上的元素?

I've already been looking for this, but I don't really know how to call this and therefore I didn't find anything useful. Apologies if this question already hangs around somewhere...

我已经找过了,但是我不知道怎么称呼它,所以我没有发现任何有用的东西。如果这个问题已经在某个地方出现了,我很抱歉……

1 个解决方案

#1


3  

We can use row/column indexing to extract the elements corresponding to 'x' and 'y' indices and then get the sum

我们可以使用行/列索引提取与'x'和'y'指标对应的元素,然后得到和

sum(y[cbind(1:nrow(y), x)])
#[1] 2

If the values are different than 1,

如果值与1不同,

sum(y[cbind(1:nrow(y), x)]==1)

Or for this case,

对于这种情况,

sum(diag(y)==1)
#[1] 2

Or

sum(y*diag(y))

EDIT: Changed the row/column index from cbind(x,1:ncol(y)) to cbind(1:nrow(y), x) as per the comments.

编辑:根据注释将行/列索引从cbind(x,1:ncol(y))更改为cbind(1:nrow(y), x)。

#1


3  

We can use row/column indexing to extract the elements corresponding to 'x' and 'y' indices and then get the sum

我们可以使用行/列索引提取与'x'和'y'指标对应的元素,然后得到和

sum(y[cbind(1:nrow(y), x)])
#[1] 2

If the values are different than 1,

如果值与1不同,

sum(y[cbind(1:nrow(y), x)]==1)

Or for this case,

对于这种情况,

sum(diag(y)==1)
#[1] 2

Or

sum(y*diag(y))

EDIT: Changed the row/column index from cbind(x,1:ncol(y)) to cbind(1:nrow(y), x) as per the comments.

编辑:根据注释将行/列索引从cbind(x,1:ncol(y))更改为cbind(1:nrow(y), x)。