通过索引矩阵

时间:2017-11-22 22:12:02

标签: r matrix indexing

我有一个对称的稀疏矩阵,初始化为零:

library(Matrix)
set.seed(1)
mat <- Matrix(0,5,5)

然后我有一个矩阵(idx.mat),它为mat中的每一行指定三个列索引,这些索引应填充另一个矩阵(val.mat)给出的值:

idx.mat <- do.call(rbind,lapply(1:5,function(i) sample(1:5,3,replace=F)))
val.mat <- matrix(runif(15,1,10),5,3)

所以我想知道根据matidx.mat填充val.mat是否有更快的方式来填充:

mat <- do.call(rbind,lapply(1:nrow(mat),function(i) {
  mat[i,idx.mat[i,]] <- val.mat[i,]
  return(mat[i,])
}))

2 个答案:

答案 0 :(得分:1)

更好的方法是将idx.mat转换为n x 2矩阵,其中列对应于行和列索引:

idx = cbind(rep(1:nrow(idx.mat), ncol(idx.mat)), c(idx.mat))

然后你可以使用那个矩阵来索引并只分配:

mat[idx] = c(val.mat)
mat
# 5 x 5 sparse Matrix of class "dgCMatrix"
#                                                  
# [1,] .        5.479293 .        4.475027 9.412347
# [2,] 2.909283 .        1.120513 .        7.458567
# [3,] .        4.441492 6.865064 .        9.927155
# [4,] 4.420317 .        .        8.827218 2.129996
# [5,] .        3.404986 4.063141 7.997007 . 

答案 1 :(得分:1)

您还可以从一开始就定义并声明sparseMatrix

# Index/value dataframe
df.idx <- cbind.data.frame(
    melt(idx.mat)[, -2],
    melt(val.mat)[, "value"]);
names(df.idx) <- c("i", "j", "x");

# Declare and define sparseMatrix
mat <- sparseMatrix(i = df.idx$i, j = df.idx$j, x = df.idx$x);
mat;
#5 x 5 sparse Matrix of class "dgCMatrix"
#
#[1,] .        5.479293 .        4.475027 9.412347
#[2,] 2.909283 .        1.120513 .        7.458567
#[3,] .        4.441492 6.865064 .        9.927155
#[4,] 4.420317 .        .        8.827218 2.129996
#[5,] .        3.404986 4.063141 7.997007 .    

或没有melt + df.idx绕道而行:

i <- rep(seq(1:nrow(idx.mat)), ncol(idx.mat));
j <- c(idx.mat);
x <- c(val.mat);
mat <- sparseMatrix(i = i, j = j, x = x);

#5 x 5 sparse Matrix of class "dgCMatrix"
#
#[1,] .        5.479293 .        4.475027 9.412347
#[2,] 2.909283 .        1.120513 .        7.458567
#[3,] .        4.441492 6.865064 .        9.927155
#[4,] 4.420317 .        .        8.827218 2.129996
#[5,] .        3.404986 4.063141 7.997007 .