2020-12-21

How to create a symmetric matrix in R

Title

Problem

We want to create a symmetric matrix based on the following example.

Example

  V1 V2 V3 V4 V5
1  0  2  3  4  5
2  0  0  6  8 10
3  0  0  0 12 15
4  0  0  0  0 20
5  0  0  0  0  0
df <- structure(list(V1 = c(0L, 0L, 0L, 0L, 0L), V2 = c(2L, 0L, 0L, 
0L, 0L), V3 = c(3L, 6L, 0L, 0L, 0L), V4 = c(4L, 8L, 12L, 0L, 
0L), V5 = c(5L, 10L, 15L, 20L, 0L)), .Names = c("V1", "V2", "V3", 
"V4", "V5"), class = "data.frame", row.names = c("1", "2", "3", 
"4", "5"))

Solution

  • Adding the transpose of the matrix.
  • df + t(df)
  • Function lower.tri
  • We assign to the lower triangle of the matrix the transpose of the lower triangle.

    df[lower.tri(df)] <- t(df)[lower.tri(df)]
      V1 V2 V3 V4 V5
    1  0  2  3  4  5
    2  2  0  6  8 10
    3  3  6  0 12 15
    4  4  8 12  0 20
    5  5 10 15 20  0

    Using upper.tri would not create a symmetrical matrix.

    df[lower.tri(df)] <- df[upper.tri(df)]
      V1 V2 V3 V4 V5
    1  0  2  3  4  5
    2  2  0  6  8 10
    3  3  8  0 12 15
    4  6 12 10  0 20
    5  4  5 15 20  0
    

References

No hay comentarios:

Publicar un comentario

Nube de datos