R 按行顺序提取上三角形的值

R 按行顺序提取上三角形的值,r,rows,R,Rows,我有以下矩阵: mat <- matrix(1:16, 4, 4) > mat [,1] [,2] [,3] [,4] [1,] 1 5 9 13 [2,] 2 6 10 14 [3,] 3 7 11 15 [4,] 4 8 12 16 mat [,1] [,2] [,3] [,4] [1,] 1 5 9 13 [2,] 2 6 10 14 [3,

我有以下矩阵:

mat <- matrix(1:16, 4, 4)

> mat
     [,1] [,2] [,3] [,4]
[1,]    1    5    9   13
[2,]    2    6   10   14
[3,]    3    7   11   15
[4,]    4    8   12   16
mat
[,1] [,2] [,3] [,4]
[1,]    1    5    9   13
[2,]    2    6   10   14
[3,]    3    7   11   15
[4,]    4    8   12   16
我想将上部三角形(不带对角线)按行顺序转换为向量: 如果我告诉你:

> mat1<-as.vector(mat[upper.tri(mat)])
> mat1
[1]  5  9 10 13 14 15
>mat1 mat1
[1]  5  9 10 13 14 15

我想按行顺序得到向量(mat1),如下所示:
5,9,13,10,14,15
我们可以进行转置,取
较低的。tri

t(mat)[lower.tri(t(mat))]
#[1]  5  9 13 10 14 15
你也可以试试这个:

indices <- which(upper.tri(mat, diag=FALSE), arr.ind=TRUE)
mat[indices[order(indices[,1]),]]
# [1]  5  9 13 10 14 15

索引一些代数技巧和一些模糊函数适用于此解决方案<代码>utMat在我之前的许多回答中,很少有人连续投我反对票,也没有解释我不明白的任何原因,谢谢你注意到@Rich ScrivenI uppoted!非常感谢您的回答@SandipanDey!非常感谢@Avi