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...
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With