Replace the lower or the upper triangular part of a (correlation) matrix.

replace_triangle(x, triangle = c("lower", "upper"), by = "", diagonal = FALSE)

replace_upper_triangle(x, by = "", diagonal = FALSE)

replace_lower_triangle(x, by = "", diagonal = FALSE)

Arguments

x

a (correlation) matrix

triangle

the triangle to replace. Allowed values are one of "upper" and "lower".

by

a replacement argument. Appropriate values are either "" or NA. Used to replace the upper, lower or the diagonal part of the matrix.

diagonal

logical. Default is FALSE. If TRUE, the matrix diagonal is included.

Value

an object of class cor_mat_tri, which is a data frame

Functions

  • replace_triangle(): replaces the specified triangle by empty or NA.

  • replace_upper_triangle(): replaces the upper triangular part of a matrix. Returns an object of class lower_tri.

  • replace_lower_triangle(): replaces the lower triangular part of a matrix. Returns an object of class lower_tri

See also

Examples

# Compute correlation matrix and pull triangles
#::::::::::::::::::::::::::::::::::::::::::
# Correlation matrix
 cor.mat <- mtcars %>%
   select(mpg, disp, hp, drat, wt, qsec) %>%
   cor_mat()
 cor.mat
#> # A tibble: 6 × 7
#>   rowname   mpg  disp    hp   drat    wt   qsec
#> * <chr>   <dbl> <dbl> <dbl>  <dbl> <dbl>  <dbl>
#> 1 mpg      1    -0.85 -0.78  0.68  -0.87  0.42 
#> 2 disp    -0.85  1     0.79 -0.71   0.89 -0.43 
#> 3 hp      -0.78  0.79  1    -0.45   0.66 -0.71 
#> 4 drat     0.68 -0.71 -0.45  1     -0.71  0.091
#> 5 wt      -0.87  0.89  0.66 -0.71   1    -0.17 
#> 6 qsec     0.42 -0.43 -0.71  0.091 -0.17  1    

 # Replace upper triangle by NA
#::::::::::::::::::::::::::::::::::::::::::
cor.mat %>% replace_upper_triangle(by = NA)
#>   rowname   mpg  disp    hp   drat    wt qsec
#> 1     mpg    NA    NA    NA     NA    NA   NA
#> 2    disp -0.85    NA    NA     NA    NA   NA
#> 3      hp -0.78  0.79    NA     NA    NA   NA
#> 4    drat  0.68 -0.71 -0.45     NA    NA   NA
#> 5      wt -0.87  0.89  0.66 -0.710    NA   NA
#> 6    qsec  0.42 -0.43 -0.71  0.091 -0.17   NA


# Replace upper triangle by NA and reshape the
# correlation matrix to have unique combinations of variables
#::::::::::::::::::::::::::::::::::::::::::
cor.mat %>%
  replace_upper_triangle(by = NA) %>%
  cor_gather()
#>    var1 var2    cor        p
#> 1  disp  mpg -0.850 9.38e-10
#> 2    hp  mpg -0.780 1.79e-07
#> 3  drat  mpg  0.680 1.78e-05
#> 4    wt  mpg -0.870 1.29e-10
#> 5  qsec  mpg  0.420 1.71e-02
#> 6    hp disp  0.790 7.14e-08
#> 7  drat disp -0.710 5.28e-06
#> 8    wt disp  0.890 1.22e-11
#> 9  qsec disp -0.430 1.31e-02
#> 10 drat   hp -0.450 9.99e-03
#> 11   wt   hp  0.660 4.15e-05
#> 12 qsec   hp -0.710 5.77e-06
#> 13   wt drat -0.710 4.78e-06
#> 14 qsec drat  0.091 6.20e-01
#> 15 qsec   wt -0.170 3.39e-01