[英]Filling in a matrix from a list of row,column,value
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
. 我想用这些值填充矩阵,以使每个
value
都精确地出现row
和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? 但是是否肯定有更优雅的方法可以在R中完成此操作?
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: 您还可以考虑使用Matrix包构建稀疏矩阵:
library(Matrix)
mat <- sparseMatrix(i = combs$row, j = combs$column, x = combs$value,
dims = c(10, 10))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.