[英]Assigning values to matrix in R - values go in every row at different columns
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
}
期望的輸出:
[1,] 1 1 1 1 . . . .
[2,] . . . . 1 1 1 1
這是有效的,但它非常慢,因為我必須為1000萬行。 在R中有更好的方法嗎?
使用矩陣索引,它使用行/列的兩列矩陣來確定更改了哪些單元格:
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.