R/根据下三角元素的向量创建对称矩阵 [英] R / creating a symmetric matrix out of the vector of the lower triangle elements

查看:72
本文介绍了R/根据下三角元素的向量创建对称矩阵的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

已向我提供了一些可以向量形式在R中使用的数据.大小为n(n + 1)/2的向量的元素应在对称矩阵中重新排列. 示例:

I was provided some data to work with in R in vector form. The elements of this vector of size n(n+1)/2 should be rearranged in a symmetric matrix. Example:

n<-4
x<-seq(from=1,to=n*(n+1)/2) 

有什么好方法

mat<- 1 2 3 4
      2 5 6 7
      3 6 8 9  
      4 7 9 10 

推荐答案

我们可以使用lower.tri

 m1 <- matrix(, n, n)
 m1[lower.tri(m1, diag=TRUE)] <- x
 m2 <- t(m1)
 m2[lower.tri(m2, diag=TRUE)] <- x

或者不执行最后两个步骤

Or instead of doing the last two steps

 pmax(m1, t(m1), na.rm=TRUE)
 #      [,1] [,2] [,3] [,4]
 #[1,]    1    2    3    4
 #[2,]    2    5    6    7
 #[3,]    3    6    8    9
 #[4,]    4    7    9   10

这篇关于R/根据下三角元素的向量创建对称矩阵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆