Reputation: 10203
I have a data frame that contains a list of row positions, column positions and values, like so:
combs <- as.data.frame(t(combn(1:10,2)))
colnames(combs) <- c('row','column')
combs$value <- rnorm(nrow(combs))
I would like to fill in a matrix with these values such that every value
appears in the matrix in exactly the position specified by row
and column
. I suppose I could do this manually
mat <- matrix(nrow=10,ncol=10)
for(i in 1:nrow(combs)) {
mat[combs[i,'row'],combs[i,'column']] <- combs[i,'value']
}
But surely there is a more elegant way to accomplish this in R?
Upvotes: 3
Views: 2273
Reputation: 89097
Like this:
mat <- matrix(nrow = 10, ncol = 10)
mat[cbind(combs$row, combs$column)] <- combs$value
You could also consider building a sparse matrix using the Matrix package:
library(Matrix)
mat <- sparseMatrix(i = combs$row, j = combs$column, x = combs$value,
dims = c(10, 10))
Upvotes: 5