Replace Lower and Upper Triangular Part of a Matrix
Source:R/replace_triangle.R
replace_triangle.RdReplace the lower or the upper triangular part of a (correlation) matrix.
Usage
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.
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 classlower_tri.replace_lower_triangle(): replaces the lower triangular part of a matrix. Returns an object of classlower_tri
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.380327e-10
#> 2 hp mpg -0.780 1.787835e-07
#> 3 drat mpg 0.680 1.776240e-05
#> 4 wt mpg -0.870 1.293959e-10
#> 5 qsec mpg 0.420 1.708199e-02
#> 6 hp disp 0.790 7.142679e-08
#> 7 drat disp -0.710 5.282022e-06
#> 8 wt disp 0.890 1.222320e-11
#> 9 qsec disp -0.430 1.314404e-02
#> 10 drat hp -0.450 9.988772e-03
#> 11 wt hp 0.660 4.145827e-05
#> 12 qsec hp -0.710 5.766253e-06
#> 13 wt drat -0.710 4.784260e-06
#> 14 qsec drat 0.091 6.195826e-01
#> 15 qsec wt -0.170 3.388683e-01