R: Reorder a Matrix Based on Hierarchical Clustering

cluster_matrix {textshape} | R Documentation

## Reorder a Matrix Based on Hierarchical Clustering

### Description

Reorder matrix rows, columns, or both via hierarchical clustering.

### Usage

    cluster_matrix(x, dim = "both", method = "ward.D2", ...)

### Arguments

`x` | A matrix.
`dim` | The dimension to reorder (cluster); must be set to "row", "col", or "both".
`method` | The agglomeration method to be used (see `hclust`).
`...` | ignored.

### Value

Returns a reordered matrix.

### See Also

`hclust`

### Examples

    cluster_matrix(mtcars)
    cluster_matrix(mtcars, dim = 'row')
    cluster_matrix(mtcars, dim = 'col')

    ## Not run:
    if (!require("pacman")) install.packages("pacman")
    pacman::p_load(tidyverse, viridis, gridExtra)

    ## plot heatmap w/o clustering
    wo <- mtcars %>%
        cor() %>%
        tidy_matrix('car', 'var') %>%
        ggplot(aes(var, car, fill = value)) +
             geom_tile() +
             scale_fill_viridis(name = expression(r[xy])) +
             theme(
                 axis.text.y = element_text(size = 8)   ,
                 axis.text.x = element_text(
                     size = 8,
                     hjust = 1,
                     vjust = 1,
                     angle = 45
                 ),
                 legend.position = 'bottom',
                 legend.key.height = grid::unit(.1, 'cm'),
                 legend.key.width = grid::unit(.5, 'cm')
             ) +
             labs(subtitle = "With Out Clustering")

    ## plot heatmap w clustering
    w <- mtcars %>%
        cor() %>%
        cluster_matrix() %>%
        tidy_matrix('car', 'var') %>%
        mutate(
            var = factor(var, levels = unique(var)),
            car = factor(car, levels = unique(car))
        ) %>%
        group_by(var) %>%
        ggplot(aes(var, car, fill = value)) +
             geom_tile() +
             scale_fill_viridis(name = expression(r[xy])) +
             theme(
                 axis.text.y = element_text(size = 8)   ,
                 axis.text.x = element_text(
                     size = 8,
                     hjust = 1,
                     vjust = 1,
                     angle = 45
                 ),
                 legend.position = 'bottom',
                 legend.key.height = grid::unit(.1, 'cm'),
                 legend.key.width = grid::unit(.5, 'cm')
             ) +
             labs(subtitle = "With Clustering")

    gridExtra::grid.arrange(wo, w, ncol = 2)

    ## End(Not run)

[Package textshape version 1.6.0 Index]