Home > database >  Summing together the lower triangle and the upper triangle of a matrix in R
Summing together the lower triangle and the upper triangle of a matrix in R

Time:10-06

I have a matrix in which the row_names and col_names are identical. The values filling the matrix are not symmetrical (i.e. the upper triangle and the lower triangle are different). The diagonal is populated with 0s.

I want to sum the upper triangle to the lower triangle.

I don't mind what format the output is in: either a data-table of the rownames-colnames- newvalues, OR a triangular matrix (rather than a square).

The attached image shows how the col-names and row-names are equal. Eventually I want a matrix that shows e.g. for M10/M10.09 = 36 36 = 72

CodePudding user response:

Use t() to transpose the matrix, and then add to the original matrix.

Other helpful matrix functions are upper.tri(), lower.tri(), and diag(). For example, filling the upper triangle with zeros.

m<-matrix(c(0,36,3,36,0,4,1,2,0), ncol=3)

m
     [,1] [,2] [,3]
[1,]    0   36    1
[2,]   36    0    2
[3,]    3    4    0

m2<-m t(m)

m2[upper.tri(m2)]<-0

m2
     [,1] [,2] [,3]
[1,]    0    0    0
[2,]   72    0    0
[3,]    4    6    0

CodePudding user response:

M.Viking's answer has all you need if you want a matrix output, this is how you would get

a data-table of the rownames-colnames- newvalues

m<-matrix(c(0,36,3,36,0,4,1,2,0), ncol=3)
msum <- m   t(m)
msum[upper.tri(msum, diag = TRUE)] <- NA                # set diag and upper tri to NA
mdf <- as.data.frame.table(msum)                        # turn into a data frame
colnames(mdf) <- c("rownames", "colnames", "newvalues") # name df columns
mdf <- mdf[!is.na(mdf$newvalues),]                      # drop all those NA rows
mdf

  rownames colnames newvalues
2        B        A        72
3        C        A         4
6        C        B         6
  • Related