[R] Need help on upper.tri()
David Winsemius
dwinsemius at comcast.net
Tue Aug 3 17:36:28 CEST 2010
On Aug 3, 2010, at 7:36 AM, Ron Michael wrote:
> HI, I am really messing up to make a symmetrical matrix using
> upper.tri() & lower.tri() function. Here is my code:
>
>> set.seed(1)
>> mat = matrix(rnorm(25), 5, 5)
>> mat
> [,1] [,2] [,3] [,4] [,5]
> [1,] -0.6264538 -0.8204684 1.5117812 -0.04493361 0.91897737
> [2,] 0.1836433 0.4874291 0.3898432 -0.01619026 0.78213630
> [3,] -0.8356286 0.7383247 -0.6212406 0.94383621 0.07456498
> [4,] 1.5952808 0.5757814 -2.2146999 0.82122120 -1.98935170
> [5,] 0.3295078 -0.3053884 1.1249309 0.59390132 0.61982575
>> mat[lower.tri(mat)] = mat[upper.tri(mat)]
>> mat
> [,1] [,2] [,3] [,4] [,5]
> [1,] -0.62645381 -0.82046838 1.51178117 -0.04493361 0.91897737
> [2,] -0.82046838 0.48742905 0.38984324 -0.01619026 0.78213630
> [3,] 1.51178117 -0.01619026 -0.62124058 0.94383621 0.07456498
> [4,] 0.38984324 0.94383621 0.78213630 0.82122120 -1.98935170
> [5,] -0.04493361 0.91897737 0.07456498 -1.98935170 0.61982575
>
>
> Which is not coming as symmetrical function. Can anyone point me on
> the correct way of using upper, lower.try() function to get a
> symmetrical matrix?
I didn't get the "tri" functions to work but perhaps this solution
with row() and col() will help you construct approach. (Plus, if this
is homework, I will not have given you the answer.)
mat2 <- mat;
mat2[row(mat) >= col(mat)] <- t(mat)[row(mat) >= col(mat)]
mat2
(Actually, following my own advice, I now see the correct "tri"
approach.)
--
David Winsemius, MD
West Hartford, CT
More information about the R-help
mailing list