To find the row and column index for upper triangular matrix elements in R, we can follow the below steps −
Let’s create a matrix as shown below −
M<-matrix(1:25,nrow=5) M
On executing, the above script generates the below output(this output will vary on your system due to randomization) −
[,1] [,2] [,3] [,4] [,5] [1,] 1 6 11 16 21 [2,] 2 7 12 17 22 [3,] 3 8 13 18 23 [4,] 4 9 14 19 24 [5,] 5 10 15 20 25
Using which function with upper.tri function to find the row and column for upper triangular matrix in M −
M<-matrix(1:25,nrow=5) Index<-which(upper.tri(M,diag=TRUE),arr.ind=TRUE) Index
row col [1,] 1 1 [2,] 1 2 [3,] 2 2 [4,] 1 3 [5,] 2 3 [6,] 3 3 [7,] 1 4 [8,] 2 4 [9,] 3 4 [10,] 4 4 [11,] 1 5 [12,] 2 5 [13,] 3 5 [14,] 4 5 [15,] 5 5
Using cbind function to attach the matrix values to indices for row and column −
M<-matrix(1:25,nrow=5) Index<-which(upper.tri(M,diag=TRUE),arr.ind=TRUE) cbind(Index,M[Index])
row col [1,] 1 1 1 [2,] 1 2 6 [3,] 2 2 7 [4,] 1 3 11 [5,] 2 3 12 [6,] 3 3 13 [7,] 1 4 16 [8,] 2 4 17 [9,] 3 4 18 [10,] 4 4 19 [11,] 1 5 21 [12,] 2 5 22 [13,] 3 5 23 [14,] 4 5 24 [15,] 5 5 25