Incrementing to matrix using indexing

Viewed 62

Is there a way to increment particular rows and columns of a matrix using indexing of that matrix and in the same time do it twice if the indices repeat. For example, with the following code:


rows <- c(1, 2, 3, 4, 1)
cols <- c(4, 2, 5, 1, 4)
freq <- matrix(0, 5, 5)

freq[cbind(rows, cols)] <- freq[cbind(rows, cols)] + 1
freq

I get ones on the particular rows and columns, but since the (1, 4) combination is repeated twice, I would like to find a way to add another 1 to it and make it two in a computationally efficient way using R's indexing of matrix like above.

Thanks in advance!

2 Answers

If you don't mind using igraph package, you can manage it via get.adjacency

library(igraph)
get.adjacency(
  graph_from_data_frame(data.frame(rows, cols), vertices = data.frame(1:nrow(freq))),
  sparse = FALSE
)

which gives

  1 2 3 4 5
1 0 0 0 2 0
2 0 1 0 0 0
3 0 0 0 0 1
4 1 0 0 0 0
5 0 0 0 0 0

We can do a group by sum with aggregate to create a new data.frame 'out'. From that, convert the 'row/col' columns to matrix and assign the 'val' column output to freq

out <- aggregate(val ~ rows + cols, cbind(rows, cols, val = 1), sum)
freq[as.matrix(out[1:2])] <- out$val

-output

freq
#     [,1] [,2] [,3] [,4] [,5]
#[1,]    0    0    0    2    0
#[2,]    0    1    0    0    0
#[3,]    0    0    0    0    1
#[4,]    1    0    0    0    0
#[5,]    0    0    0    0    0
Related