blm*_*ore 13 r matrix slice diagonal
我有一个很大的nxn矩阵,想要拍摄不同大小的非对角切片.例如:
1 2 3 4 5 6
1 2 3 4 5 6
1 2 3 4 5 6
1 2 3 4 5 6
1 2 3 4 5 6
1 2 3 4 5 6
Run Code Online (Sandbox Code Playgroud)
我想要一个R函数,当给定矩阵和"对角线切片的宽度"时,它将返回仅具有这些值的nxn矩阵.所以对于上面的矩阵,比方说3,我得到:
1 x x x x x
1 2 x x x x
1 2 3 x x x
x 2 3 4 x x
x x 3 4 5 x
x x x 4 5 6
Run Code Online (Sandbox Code Playgroud)
目前我正在使用(原谅我)一个非常慢的for循环:
getDiags<-function(ndiags, cormat){
resmat=matrix(ncol=ncol(cormat),nrow=nrow(cormat))
dimnames(resmat)<-dimnames(cormat)
for(j in 1:ndiags){
resmat[row(resmat) == col(resmat) + j] <-
cormat[row(cormat) == col(cormat) + j]
}
return(resmat)
}
Run Code Online (Sandbox Code Playgroud)
我意识到这是解决这个问题的非常"非R"方式.有没有更好的方法,可能使用diag或lower.tri?
Thi*_*rry 14
size <- 6
mat <- matrix(seq_len(size ^ 2), ncol = size)
low <- 0
high <- 3
delta <- rep(seq_len(ncol(mat)), nrow(mat)) -
rep(seq_len(nrow(mat)), each = ncol(mat))
#or Ben Bolker's better alternative
delta <- row(mat) - col(mat)
mat[delta < low | delta > high] <- NA
mat
Run Code Online (Sandbox Code Playgroud)
这适用于我的机器上的5000 x 5000矩阵