Search code examples
rperformancematrixindices

Increment a matrix based on another matrix of indices


I have a matrix:

a <- matrix(0,nrow=26,ncol=26)
tags <- sample(letters)
colnames(a) <- tags
rownames(a) <- tags

and another matrix:

b <- matrix(c(1,2,1,2,1,2,3,5,5,5),nrow=5,ncol=2)

I want to increment all cells in a whose indices are specified in each row of b

This would induce the following changes:

a[b[1,1],b[1,2]] <- a[b[1,1],b[1,2]] +1
a[b[2,1],b[2,2]] <- a[b[2,1],b[2,2]] +1
...

I am looking for an efficient solution preferably one that doesn't involve loops


Solution

  • You can try this one:

    library(dplyr)
    countB <- data.frame(b) %>% group_by(X1, X2) %>% summarise(Count = n())
    a[as.matrix(countB[-3])] <- countB[[3]]