Search code examples
rdendrogramhclustggdendro

For hclust1a-->dendrogram-->hclust1b in R, why plot for hclust1a and hclust1b differs?


I have a hclust object named hc1a. I convert it to a dendrogram object, which is in turn converted back to a hclust object and name it as hc1b:

# Create hc1a and plot
hc1a <- list()
hc1a$merge <- matrix(c(-8, -9,
                      -1, -2,
                      -5,  1,
                      -7,  2,
                      -3,  4,
                       3,  5,
                      -4,  6,
                      -6,  7), ncol = 2, byrow = T)
hc1a$height <- c(0.01333333, 0.02000000, 0.03833333, 0.05500000, 0.06888889, 0.10555556, 0.13285714, 0.19625000)
hc1a$order <- c(4, 3, 2, 1, 7, 5, 9, 8, 6)           
hc1a$labels <- c(4136, 4137, 4139, 4141, 4292, 4302, 4303, 4305, 4306)
class(hc1a) <- "hclust" 
plot(hc1a)

enter image description here

# Create hc1b and plot
hc1b <- as.hclust(as.dendrogram(hc1a))
plot(hc1b)

enter image description here

Why does dendrogram for hc1a and hc1b differ? How to preserve the structure of dendrogram for hc1a in hc1b? That is to say, I want to convert hc1a to a dendrogram object and convert that dendrogram object back to a new hclust object named hc1b. When hc1b is plotted, I want it to be identical to plot(hc1a).


Solution

  • The order changes when using as.dendrogram and as.hclust, so you could use the same order of your hc1a object like this:

    # Create hc1a and plot
    hc1a <- list()
    hc1a$merge <- matrix(c(-8, -9,
                           -1, -2,
                           -5,  1,
                           -7,  2,
                           -3,  4,
                           3,  5,
                           -4,  6,
                           -6,  7), ncol = 2, byrow = T)
    hc1a$height <- c(0.01333333, 0.02000000, 0.03833333, 0.05500000, 0.06888889, 0.10555556, 0.13285714, 0.19625000)
    hc1a$order <- c(4, 3, 2, 1, 7, 5, 9, 8, 6)           
    hc1a$labels <- c(4136, 4137, 4139, 4141, 4292, 4302, 4303, 4305, 4306)
    class(hc1a) <- "hclust" 
    plot(hc1a)
    

    # Create hc1b and plot
    hc1b <- as.hclust(as.dendrogram(hc1a, check = TRUE))
    hc1b$order = hc1a$order
    plot(hc1b)
    

    Created on 2023-04-21 with reprex v2.0.2