[英]Summing together the lower triangle and the upper triangle of a matrix in R
我有一個矩陣,其中 row_names 和 col_names 是相同的。 填充矩陣的值不是對稱的(即上三角和下三角不同)。 對角線用 0 填充。
我想將上三角與下三角相加。
我不介意 output 是什么格式:要么是 rownames-colnames-newvalues 的 data.table,要么是三角矩陣(而不是正方形)。
使用t()
轉置矩陣,然后添加到原始矩陣。
其他有用的矩陣函數是upper.tri()
、 lower.tri()
和diag()
。 例如,用零填充上三角。
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
如果你想要一個矩陣 output, M.Viking 的答案有你需要的一切,這就是你得到的方式
rownames-colnames-newvalues 的 data.table
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.