我想将函数的返回向量重新排列为下三角矩阵。如
resultF <- function(data){ # for example
rw <- nrow(data)
res <- matrix(0, rw, rw)
res[lower.tri(res)] <- 1
return (sort(c(res), decreasing = T))
}
r <- 6
c <- 2
data <- matrix(rnorm(100), r, c)
result <- resultF(data) # function returns 6 * 6 vector with first elements of the vector containing the values of the lower triangle in this case 36 elements returned, and 1-15 are lower triangle values.
这给了我想要的东西,我的问题是,有没有更好的方法呢?
mat <- matrix(0, r, r)
mmt <- mat[lower.tri(mat)]
size <- length(mmt)
val <- result[1:size]
mat[lower.tri(mat)] <- val
mat
输出:
> mat
[,1] [,2] [,3] [,4] [,5] [,6]
[1,] 0 0 0 0 0 0
[2,] 1 0 0 0 0 0
[3,] 1 1 0 0 0 0
[4,] 1 1 1 0 0 0
[5,] 1 1 1 1 0 0
[6,] 1 1 1 1 1 0