Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get all elements at indices stored in a vector?

Tags:

indexing

r

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

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.

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?

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...

like image 487
Mr Tsjolder Avatar asked Jan 29 '26 10:01

Mr Tsjolder


1 Answers

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

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

If the values are different than 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.

like image 110
akrun Avatar answered Jan 31 '26 00:01

akrun