I have a dataframe/matrix of equal rows and columns. I want to extract only the upper or lower triangle.
x<-data.frame(matrix(1:25,nrow=5))
colnames(x)<-LETTERS[1:5]
rownames(x)<-LETTERS[1:5]
x[upper.tri(x,diag=F)]
From this result, it is not possible to say what combination of column and row the value came from. So, I would like to have the row and column attributes in the results. Something like this:
Col Row Val
B A 6
C A 11
C B 12
...
I need to do this for a large correlation matrix. Thanks.
A square matrix is called lower triangular if all the entries above the main diagonal are zero. Examples: Input : mat[4][4] = {{1, 0, 0, 0}, {1, 4, 0, 0}, {4, 6, 2, 0}, {0, 4, 7, 6}}; Output : Matrix is in lower triangular form.
The set of all possible variances and covariances between velocities in the three Cartesian directions, defined for a specified statistical order or moment. For example, the second moment correlation triangle is. where squared quantities are velocity variances and the other terms are covariances.
the upper triangular of a matrix is the top right triangle, in this case we are masking out the upper triangle of the matrix and just showing the lower triangle part of it. This is because a correlation matrix is symmetric.
Method 1: Creating a correlation matrix using Numpy libraryNumpy library make use of corrcoef() function that returns a matrix of 2×2. The matrix consists of correlations of x with x (0,0), x with y (0,1), y with x (1,0) and y with y (1,1).
I'd just use which
with arr.ind = TRUE
like this:
ind <- which( upper.tri(x,diag=F) , arr.ind = TRUE )
data.frame( col = dimnames(x)[[2]][ind[,2]] ,
row = dimnames(x)[[1]][ind[,1]] ,
val = x[ ind ] )
col row val
1 B A 6
2 C A 11
3 C B 12
4 D A 16
5 D B 17
6 D C 18
7 E A 21
8 E B 22
9 E C 23
10 E D 24
First, to make things unambiguous, I change
colnames(x) <- LETTERS[6:10]
Use expand.grid
to get the row and column names like this
rowCol <- expand.grid(rownames(x), colnames(x))
To get the correct rows from this data frame, take
labs <- rowCol[as.vector(upper.tri(x,diag=F)),]
df <- cbind(labs, x[upper.tri(x,diag=F)])
colnames(df) <- c("Row","Col","Val")
df[,c(2,1,3)]
## Col Row Val
## 6 G A 6
## 11 H A 11
## ...
... this might be a solution
nam <-apply(ind, 2, function(y, x) rownames(x)[c(y)], x=x)
cbind(nam, x[upper.tri(x,diag=F)])
hth
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With