在R值中为矩阵赋值——在不同列的每一行中

时间:2021-05-09 13:21:42
nr <- 2
nc <- 4
rxc <- nr*nc
m1 <- Matrix(0, nrow = nr, ncol = rxc, sparse = TRUE)
col <- 0
for(r in 1:nr){
  m1[r,((r-1)*nc+1) :(((r-1)*nc+1)+3)] <- 1
  col <- col+1
}

Desired Output:

期望的输出:

[1,] 1 1 1 1 . . . .
[2,] . . . .    1 1 1 1

This works, but its very slow as I have to do it for 10 Million rows. Is there any better way do it in R ?

这是可行的,但它非常慢,因为我要用1000万行。有没有更好的方法用R表示?

1 个解决方案

#1


3  

Use matrix indexing, which uses a two column matrix of row/column to determine which cells are changed:

使用矩阵索引,使用行/列的两列矩阵来确定哪些单元格被更改:

m1[cbind(rep(1:nr,each=nc),1:(nr*nc))] <- 1
m1
#2 x 8 sparse Matrix of class "dgCMatrix"
#                    
#[1,] 1 1 1 1 . . . .
#[2,] . . . . 1 1 1 1

#1


3  

Use matrix indexing, which uses a two column matrix of row/column to determine which cells are changed:

使用矩阵索引,使用行/列的两列矩阵来确定哪些单元格被更改:

m1[cbind(rep(1:nr,each=nc),1:(nr*nc))] <- 1
m1
#2 x 8 sparse Matrix of class "dgCMatrix"
#                    
#[1,] 1 1 1 1 . . . .
#[2,] . . . . 1 1 1 1