[英]How to use apply family functions on an array and a matrix instead of a for loop in R?
[英]R how to use loop functions to create a matrix
我想創建一個由一系列較小的矩陣組成的大型矩陣。 有30個小的30 x 3153矩陣。 每個只有1行,其余均為0。 1s行的位置從1到30。例如,在第1個矩陣中,1s在第1行,第2個矩陣在第2行,依此類推。
由於我是編程新手,所以我不確定如何使用循環函數來實現此目的。 我不知道如何將變量傳遞給循環函數。
這是我嘗試過的。
我對如何使用循環來完成此工作感到困惑。 如果有人可以幫助我,我將不勝感激。 謝謝
vec0=rep.int(0,n)
vec1=rep.int(1,n)
uij=matrix(rep(vec0,c-1),nrow=c-1,ncol=n)
Uij=cbind(lapply(uij,insertRow(uij,i,vec1)))
hold_mat <- list()
for(i in seq(30)){
mat <- matrix(0, nrow = 30, ncol = 3153)
mat[i, ] <- 1
hold_mat[[i]] <- mat
}
bigMatrix <- do.call(rbind, hold_mat)
編輯:這是來自Matrix
包的稀疏矩陣的解決方案:
library(Matrix)
numRows <- 30
numCols <- 3152
hold_mat <- lapply(seq(numRows), function(k) sparseMatrix(i = rep(k, numCols), j = seq(numCols), dims = c(numRows, numCols)))
bigMatrix <- do.call(rBind, hold_mat)
> str(bigMatrix)
Formal class 'ngCMatrix' [package "Matrix"] with 5 slots
..@ i : int [1:94560] 0 31 62 93 124 155 186 217 248 279 ...
..@ p : int [1:3153] 0 30 60 90 120 150 180 210 240 270 ...
..@ Dim : int [1:2] 900 3152
..@ Dimnames:List of 2
.. ..$ : NULL
.. ..$ : NULL
..@ factors : list()
考慮一下大矩陣的每一行是什么樣的:
1 - 29 times 0 - 0 - 1 - 28 times 0 - 0 - 0 - 1 - 27 times 0 - ...
因此,基本上,您有:
[1 - 30 times 0] x 30 times - 1
重復3153行。
因此,您可以使用:
row <- c(rep( c(1, rep(0, 30)), 30), 1)
m <- matrix(rep(row, 3153), nrow=3153)
哪里:
c(1, rep(0, 30)) # one followed by 30 zeros
rep( c(1, rep(0, 30)), 30) # 1 and 30x 0 repeated 30 times
c(rep( c(1, rep(0, 30)), 30), 1) # 1 and 30x 0 rep 30 times and 1 at the end
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.