r - Filling in a matrix from a list of row,column,value -


i have data frame contains list of row positions, column positions , values, so:

combs <- as.data.frame(t(combn(1:10,2))) colnames(combs) <- c('row','column') combs$value <- rnorm(nrow(combs)) 

i fill in matrix these values such every value appears in matrix in position specified row , column. suppose 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 more elegant way accomplish in r?

like this:

mat <- matrix(nrow = 10, ncol = 10) mat[cbind(combs$row, combs$column)] <- combs$value 

you consider building sparse matrix using matrix package:

library(matrix) mat <- sparsematrix(i = combs$row, j = combs$column, x = combs$value,                     dims = c(10, 10)) 

Comments

Popular posts from this blog

java - WrongTypeOfReturnValue exception thrown when unit testing using mockito -

php - Magento - Deleted Base url key -

android - How to disable Button if EditText is empty ? -