<p><div><div><div><div data-show-faces="false" data-height="21" data-width="100" data-layout="button_count" data-send="true" data-href="https://www.r-bloggers.com/how-to-perform-hierarchical-clustering-using-r/"></div></div><div></div></div><div></div></div>
<div>
(This article was first published on <strong><a href="http://r-posts.com/how-to-perform-hierarchical-clustering-using-r/"> R-posts.com</a></strong>, and kindly contributed to <a rel="nofollow" href="https://www.r-bloggers.com/">R-bloggers)</a> </div>
<h2>What is Hierarchical Clustering?</h2>
<p>Clustering is a technique to club similar data points into one group and separate out dissimilar observations into different groups or clusters. In Hierarchical Clustering, clusters are created such that they have a predetermined ordering i.e. a hierarchy. For example, consider the concept hierarchy of a library. A library has many sections, each section would have many books, and the books would be grouped according to their subject, let’s say. This forms a hierarchy.<br>
In Hierarchical Clustering, this hierarchy of clusters can either be created from top to bottom, or vice-versa. Hence, it’s two types namely – Divisive and Agglomerative. Let’s discuss it in detail.</p>
<h2>Divisive Method</h2>
<p>In Divisive method we assume that all of the observations belong to a single cluster and then divide the cluster into two least similar clusters. This is repeated recursively on each cluster until there is one cluster for each observation. This technique is also called DIANA, which is an acronym for Divisive Analysis.</p>
<h2>Agglomerative Method</h2>
<p>It’s also known as Hierarchical Agglomerative Clustering (HAC) or AGNES (acronym for Agglomerative Nesting). In this method, each observation is assigned to its own cluster. Then, the similarity (or distance) between each of the clusters is computed and the two most similar clusters are merged into one. Finally, steps 2 and 3 are repeated until there is only one cluster left. </p>
<p><img data-orig-file="https://i1.wp.com/r-posts.com/wp-content/uploads/2017/12/Agnes.png?fit=731%2C462" data-orig-size="731,462" data-medium-file="https://i1.wp.com/r-posts.com/wp-content/uploads/2017/12/Agnes.png?fit=450%2C284" data-attachment-id="389" data-image-meta="{" data-image-description="" src="https://i1.wp.com/r-posts.com/wp-content/uploads/2017/12/Agnes.png?resize=450%2C284" data-permalink="http://r-posts.com/how-to-perform-hierarchical-clustering-using-r/agnes/" data-large-file="https://i1.wp.com/r-posts.com/wp-content/uploads/2017/12/Agnes.png?fit=450%2C284" alt="" data-image-title="Agnes" sizes="(max-width: 450px) 100vw, 450px" width="450" data-comments-opened="1" class="wp-image-389" data-recalc-dims="1" height="284"></p>
<p>Please note that Divisive method is good for identifying large clusters while Agglomerative method is good for identifying small clusters.<br>
We will proceed with Agglomerative Clustering for the rest of the article. Since, HAC’s account for the majority of hierarchical clustering algorithms while Divisive methods are rarely used.<br>
I think now we have a general overview of Hierarchical Clustering. Let’s also get ourselves familiarized with the algorithm for it.</p>
<h2>HAC Algorithm</h2>
<p>Given a set of N items to be clustered, and an NxN distance (or similarity) matrix, the basic process of Johnson’s (1967) hierarchical clustering is – </p>
<ol>
<li>Assign each item to its own cluster, so that if you have N items, you now have N clusters, each containing just one item. Let the distances (similarities) between the clusters equal the distances (similarities) between the items they contain.</li>
<li>
Find the closest (most similar) pair of clusters and merge them into a single cluster, so that now you have one less cluster.</li>
<li>
Compute distances (similarities) between the new cluster and each of the old clusters.</li>
<li>
Repeat steps 2 and 3 until all items are clustered into a single cluster of size N.</li>
</ol>
<p>In Steps 2 and 3 here, the algorithm talks about finding similarity among clusters. So, before any clustering is performed, it is required to determine the distance matrix that specifies the distance between each data point using some distance function (Euclidean, Manhattan, Minkowski, etc.). Then, the matrix is updated to specify the distance between different clusters that are formed as a result of merging. But, how do we measure the distance (or similarity) between two clusters of observations?<br>
For this, we have three different methods as described below. These methods differ in how the distance between each cluster is measured.</p>
<h2>Single Linkage</h2>
<p>It is also known as the connectedness or minimum method. Here, the distance between one cluster and another cluster is taken to be equal to the shortest distance from any data point of one cluster to any data point in another. That is, distance will be based on similarity of the closest pair of data points as shown in the figure. It tends to produce long, “loose” clusters.<br>
Disadvantage of this method is that it can cause premature merging of groups with close pairs, even if those groups are quite dissimilar overall. </p>
<p><img data-orig-file="https://i2.wp.com/r-posts.com/wp-content/uploads/2017/12/Single-Linkage.png?fit=717%2C552" data-orig-size="717,552" data-medium-file="https://i2.wp.com/r-posts.com/wp-content/uploads/2017/12/Single-Linkage.png?fit=390%2C300" data-attachment-id="390" data-image-meta="{" data-image-description="" src="https://i2.wp.com/r-posts.com/wp-content/uploads/2017/12/Single-Linkage.png?resize=450%2C346" data-permalink="http://r-posts.com/how-to-perform-hierarchical-clustering-using-r/single-linkage-2/" data-large-file="https://i2.wp.com/r-posts.com/wp-content/uploads/2017/12/Single-Linkage.png?fit=450%2C346" alt="" data-image-title="Single Linkage" sizes="(max-width: 450px) 100vw, 450px" width="450" data-comments-opened="1" class="wp-image-390" data-recalc-dims="1" height="346"></p>
<h2>Complete Linkage</h2>
<p>This method is also called the diameter or maximum method. In this method, we consider similarity of the furthest pair. That is, the distance between one cluster and another cluster is taken to be equal to the longest distance from any member of one cluster to any member of the other cluster. It tends to produce more compact clusters.<br>
One drawback of this method is that outliers can cause close groups to be merged later than what is optimal. </p>
<p><img data-orig-file="https://i2.wp.com/r-posts.com/wp-content/uploads/2017/12/complete-linkage.png?fit=671%2C554" data-orig-size="671,554" data-medium-file="https://i2.wp.com/r-posts.com/wp-content/uploads/2017/12/complete-linkage.png?fit=363%2C300" data-attachment-id="391" data-image-meta="{" data-image-description="" src="https://i2.wp.com/r-posts.com/wp-content/uploads/2017/12/complete-linkage.png?resize=450%2C372" data-permalink="http://r-posts.com/how-to-perform-hierarchical-clustering-using-r/complete-linkage-2/" data-large-file="https://i2.wp.com/r-posts.com/wp-content/uploads/2017/12/complete-linkage.png?fit=450%2C372" alt="" data-image-title="complete linkage" sizes="(max-width: 450px) 100vw, 450px" width="450" data-comments-opened="1" class="wp-image-391" data-recalc-dims="1" height="372"></p>
<h2>Average Linkage</h2>
<p>In Average linkage method, we take the distance between one cluster and another cluster to be equal to the average distance from any member of one cluster to any member of the other cluster.<br>
A variation on average-link clustering is the UCLUS method of D’Andrade (1978) which uses the median distance instead of mean distance. </p>
<p><img data-orig-file="https://i1.wp.com/r-posts.com/wp-content/uploads/2017/12/average-linkage.png?fit=514%2C471" data-orig-size="514,471" data-medium-file="https://i1.wp.com/r-posts.com/wp-content/uploads/2017/12/average-linkage.png?fit=327%2C300" data-attachment-id="392" data-image-meta="{" data-image-description="" src="https://i1.wp.com/r-posts.com/wp-content/uploads/2017/12/average-linkage.png?resize=450%2C412" data-permalink="http://r-posts.com/how-to-perform-hierarchical-clustering-using-r/average-linkage-2/" data-large-file="https://i1.wp.com/r-posts.com/wp-content/uploads/2017/12/average-linkage.png?fit=450%2C412" alt="" data-image-title="average linkage" sizes="(max-width: 450px) 100vw, 450px" width="450" data-comments-opened="1" class="wp-image-392" data-recalc-dims="1" height="412"></p>
<h2>Ward’s Method</h2>
<p>Ward’s method aims to minimize the total within-cluster variance. At each step the pair of clusters with minimum between-cluster distance are merged. In other words, it forms clusters in a manner that minimizes the loss associated with each cluster. At each step, the union of every possible cluster pair is considered and the two clusters whose merger results in minimum increase in information loss are combined. Here, information loss is defined by Ward in terms of an error sum-of-squares criterion (ESS). If you want a mathematical treatment of this visit <a rel="nofollow" href="https://hlab.stanford.edu/brian/error_sum_of_squares.html" target="_blank">this link</a>. </p>
<p>The following table describes the mathematical equations for each of the methods — </p>
<p><img data-orig-file="https://i1.wp.com/r-posts.com/wp-content/uploads/2017/11/table.png?fit=599%2C427" data-orig-size="599,427" data-medium-file="https://i1.wp.com/r-posts.com/wp-content/uploads/2017/11/table.png?fit=421%2C300" data-attachment-id="341" data-image-meta="{" data-image-description="" src="https://i1.wp.com/r-posts.com/wp-content/uploads/2017/11/table.png?resize=450%2C321" data-permalink="http://r-posts.com/?attachment_id=341" data-large-file="https://i1.wp.com/r-posts.com/wp-content/uploads/2017/11/table.png?fit=450%2C321" alt="" data-image-title="table" sizes="(max-width: 450px) 100vw, 450px" width="450" data-comments-opened="1" class="wp-image-341" data-recalc-dims="1" height="321"></p>
<p>Where, </p>
<ul>
<li>X1, X2, , Xk = Observations from cluster 1</li>
<li>
Y1, Y2, , Yl = Observations from cluster 2</li>
<li>
d (x, y) = Distance between a subject with observation vector x and a subject with observation vector y</li>
<li>
||.|| = Euclidean norm</li>
</ul>
<h2>Implementing Hierarchical Clustering in R</h2>
<h3>Data Preparation</h3>
<p>To perform clustering in R, the data should be prepared as per the following guidelines – </p>
<ol>
<li>Rows should contain observations (or data points) and columns should be variables.</li>
<li>
Check if your data has any missing values, if yes, remove or impute them.</li>
<li>
Data across columns must be standardized or scaled, to make the variables comparable.</li>
</ol>
<p>We’ll use a data set called ‘Freedman’ from the ‘car’ package. The ‘Freedman’ data frame has 110 rows and 4 columns. The observations are U. S. metropolitan areas with 1968 populations of 250,000 or more. There are some missing data. (Make sure you install the car package before proceeding)</p>
<pre>data &lt;- car::Freedman

To remove any missing value that might be present in the data, type this:
data &lt;- na.omit(data)
</pre>
<p>This simply removes any row that contains missing values. You can use more sophisticated methods for imputing missing values. However, we’ll skip this as it is beyond the scope of the article. Also, we will be using numeric variables here for the sake of simply demonstrating how clustering is done in R. Categorical variables, on the other hand, would require special treatment, which is also not within the scope of this article. Therefore, we have selected a data set with numeric variables alone for conciseness. </p>
<p>Next, we have to scale all the numeric variables. Scaling means each variable will now have mean zero and standard deviation one. Ideally, you want a unit in each coordinate to represent the same degree of difference. Scaling makes the standard deviation the unit of measurement in each coordinate. This is done to avoid the clustering algorithm to depend to an arbitrary variable unit. You can scale/standardize the data using the R function scale:</p>
<pre>data &lt;- scale(data)
</pre>
<h3>Implementing Hierarchical Clustering in R</h3>
<p>There are several functions available in R for hierarchical clustering. Here are some commonly used ones: </p>
<ul>
<li>‘hclust’ (stats package) and ‘agnes’ (cluster package) for agglomerative hierarchical clustering</li>
<li>
‘diana’ (cluster package) for divisive hierarchical clustering</li>
</ul>
<h2>Agglomerative Hierarchical Clustering</h2>
<p>For ‘hclust’ function, we require the distance values which can be computed in R by using the ‘dist’ function. Default measure for dist function is ‘Euclidean’, however you can change it with the method argument. With this, we also need to specify the linkage method we want to use (i.e. “complete”, “average”, “single”, “ward.D”).</p>
<pre># Dissimilarity matrix
d &lt;- dist(data, method = &quot;euclidean&quot;)
# Hierarchical clustering using Complete Linkage
hc1 &lt;- hclust(d, method = &quot;complete&quot; )
# Plot the obtained dendrogram
plot(hc1, cex = 0.6, hang = -1)
</pre>
<p><img data-orig-file="https://i0.wp.com/r-posts.com/wp-content/uploads/2017/11/cluster-dendrogram.png?fit=653%2C357" data-orig-size="653,357" data-medium-file="https://i0.wp.com/r-posts.com/wp-content/uploads/2017/11/cluster-dendrogram.png?fit=450%2C246" data-attachment-id="333" data-image-meta="{" data-image-description="" src="https://i0.wp.com/r-posts.com/wp-content/uploads/2017/11/cluster-dendrogram.png?resize=450%2C246" data-permalink="http://r-posts.com/?attachment_id=333" data-large-file="https://i0.wp.com/r-posts.com/wp-content/uploads/2017/11/cluster-dendrogram.png?fit=450%2C246" alt="" data-image-title="cluster dendrogram" sizes="(max-width: 450px) 100vw, 450px" width="450" data-comments-opened="1" class="wp-image-333" data-recalc-dims="1" height="246"></p>
<p>Another alternative is the agnes function. Both of these functions are quite similar; however, with the agnes function you can also get the agglomerative coefficient, which measures the amount of clustering structure found (values closer to 1 suggest strong clustering structure).</p>
<pre># Compute with agnes (make sure you have the package cluster)
hc2 &lt;- agnes(data, method = &quot;complete&quot;)

# Agglomerative coefficient
hc2$ac

## [1] 0.9317012
Let’s compare the methods discussed

# vector of methods to compare
m &lt;- c( &quot;average&quot;, &quot;single&quot;, &quot;complete&quot;, &quot;ward&quot;)
names(m) &lt;- c( &quot;average&quot;, &quot;single&quot;, &quot;complete&quot;, &quot;ward&quot;)

# function to compute coefficient
ac &lt;- function(x) {
  agnes(data, method = x)$ac
}
map_dbl(m, ac)      

## from ‘purrr’ package
## average single complete ward

## 0.9241325 0.9215283 0.9317012 0.9493598

Ward’s method gets us the highest agglomerative coefficient. Let us look at its dendogram.
hc3 &lt;- agnes(data, method = &quot;ward&quot;)
pltree(hc3, cex = 0.6, hang = -1, main = &quot;Dendrogram of agnes&quot;)
</pre>
<h2><img data-orig-file="https://i1.wp.com/r-posts.com/wp-content/uploads/2017/11/dendrogram-of-agnes.png?fit=653%2C357" data-orig-size="653,357" data-medium-file="https://i1.wp.com/r-posts.com/wp-content/uploads/2017/11/dendrogram-of-agnes.png?fit=450%2C246" data-attachment-id="336" data-image-meta="{" data-image-description="" src="https://i1.wp.com/r-posts.com/wp-content/uploads/2017/11/dendrogram-of-agnes.png?resize=450%2C246" data-permalink="http://r-posts.com/?attachment_id=336" data-large-file="https://i1.wp.com/r-posts.com/wp-content/uploads/2017/11/dendrogram-of-agnes.png?fit=450%2C246" alt="" data-image-title="dendrogram of agnes" sizes="(max-width: 450px) 100vw, 450px" width="450" data-comments-opened="1" class="wp-image-336" data-recalc-dims="1" height="246">
<p>Divisive Hierarchical Clustering</h2>
<p>The function ‘diana’ in the cluster package helps us perform divisive hierarchical clustering. ‘diana’ works similar to ‘agnes’. However, there is no method argument here, and, instead of agglomerative coefficient, we have divisive coefficient.</p>
<pre># compute divisive hierarchical clustering
hc4 &lt;- diana(data)

# Divise coefficient
hc4$dc

## [1] 0.9305939

# plot dendrogram
pltree(hc4, cex = 0.6, hang = -1, main = &quot;Dendrogram of diana&quot;)
</pre>
<p><img data-orig-file="https://i0.wp.com/r-posts.com/wp-content/uploads/2017/11/dendrogram-of-diana.png?fit=653%2C357" data-orig-size="653,357" data-medium-file="https://i0.wp.com/r-posts.com/wp-content/uploads/2017/11/dendrogram-of-diana.png?fit=450%2C246" data-attachment-id="339" data-image-meta="{" data-image-description="" src="https://i0.wp.com/r-posts.com/wp-content/uploads/2017/11/dendrogram-of-diana.png?resize=450%2C246" data-permalink="http://r-posts.com/?attachment_id=339" data-large-file="https://i0.wp.com/r-posts.com/wp-content/uploads/2017/11/dendrogram-of-diana.png?fit=450%2C246" alt="" data-image-title="dendrogram of diana" sizes="(max-width: 450px) 100vw, 450px" width="450" data-comments-opened="1" class="wp-image-339" data-recalc-dims="1" height="246"></p>
<p>A dendogram is a cluster tree where each group is linked to two or more successor groups. These groups are nested and organized as a tree. You could manage dendograms and do much more with them using the package “dendextend”. Check out the vignette of the package here: </p>
<p><a rel="nofollow" href="https://cran.r-project.org/web/packages/dendextend/vignettes/Quick_Introduction.html" target="_blank">https://cran.r-project.org/web/packages/dendextend/vignettes/Quick_Introduction.html</a> </p>
<p>Great! So now we understand how to perform clustering and come up with dendograms. Let us move to the final step of assigning clusters to the data points.</p>
<p>This can be done with the R function <a rel="nofollow" href="https://stat.ethz.ch/R-manual/R-devel/library/stats/html/cutree.html" target="_blank">cutree</a>. It cuts a tree (or dendogram), as resulting from <a rel="nofollow" href="https://stat.ethz.ch/R-manual/R-devel/library/stats/html/hclust.html" target="_blank">hclust</a> (or diana/agnes), into several groups either by specifying the desired number of groups (k) or the cut height (h). At least one of k or h must be specified, k overrides h if both are given.</p>
<p>Following our demo, assign clusters for the tree obtained by diana function (under section Divisive Hierarchical Clustering).</p>
<pre>clust &lt;- cutree(hc4, k = 5)</pre>
<p>We can also use the fviz_cluster function from the factoextra package to visualize the result in a scatter plot.</p>
<pre>fviz_cluster(list(data = data, cluster = clust))  ## from ‘factoextra’ package </pre>
<p><img data-orig-file="https://i2.wp.com/r-posts.com/wp-content/uploads/2017/11/cluster-plot.png?fit=653%2C357" data-orig-size="653,357" data-medium-file="https://i2.wp.com/r-posts.com/wp-content/uploads/2017/11/cluster-plot.png?fit=450%2C246" data-attachment-id="334" data-image-meta="{" data-image-description="" src="https://i2.wp.com/r-posts.com/wp-content/uploads/2017/11/cluster-plot.png?resize=450%2C246" data-permalink="http://r-posts.com/?attachment_id=334" data-large-file="https://i2.wp.com/r-posts.com/wp-content/uploads/2017/11/cluster-plot.png?fit=450%2C246" alt="" data-image-title="cluster plot" sizes="(max-width: 450px) 100vw, 450px" width="450" data-comments-opened="1" class="wp-image-334" data-recalc-dims="1" height="246"></p>
<p>You can also visualize the clusters inside the dendogram itself by putting borders as shown next </p>
<p>pltree(hc4, hang=-1, cex = 0.6) </p>
<p><img data-orig-file="https://i1.wp.com/r-posts.com/wp-content/uploads/2017/11/dendrogram-of-diana-xdata.png?fit=653%2C357" data-orig-size="653,357" data-medium-file="https://i1.wp.com/r-posts.com/wp-content/uploads/2017/11/dendrogram-of-diana-xdata.png?fit=450%2C246" data-attachment-id="337" data-image-meta="{" data-image-description="" src="https://i1.wp.com/r-posts.com/wp-content/uploads/2017/11/dendrogram-of-diana-xdata.png?resize=450%2C246" data-permalink="http://r-posts.com/?attachment_id=337" data-large-file="https://i1.wp.com/r-posts.com/wp-content/uploads/2017/11/dendrogram-of-diana-xdata.png?fit=450%2C246" alt="" data-image-title="dendrogram of diana xdata" sizes="(max-width: 450px) 100vw, 450px" width="450" data-comments-opened="1" class="wp-image-337" data-recalc-dims="1" height="246"></p>
<p>rect.hclust(hc4, k = 9, border = 2:10) </p>
<p><img data-orig-file="https://i2.wp.com/r-posts.com/wp-content/uploads/2017/11/dendrogram-of-diana-xdata2.png?fit=653%2C357" data-orig-size="653,357" data-medium-file="https://i2.wp.com/r-posts.com/wp-content/uploads/2017/11/dendrogram-of-diana-xdata2.png?fit=450%2C246" data-attachment-id="338" data-image-meta="{" data-image-description="" src="https://i2.wp.com/r-posts.com/wp-content/uploads/2017/11/dendrogram-of-diana-xdata2.png?resize=450%2C246" data-permalink="http://r-posts.com/?attachment_id=338" data-large-file="https://i2.wp.com/r-posts.com/wp-content/uploads/2017/11/dendrogram-of-diana-xdata2.png?fit=450%2C246" alt="" data-image-title="dendrogram of diana xdata2" sizes="(max-width: 450px) 100vw, 450px" width="450" data-comments-opened="1" class="wp-image-338" data-recalc-dims="1" height="246"></p>
<h2>dendextend</h2>
<h2>
</h2>
<p>You can do a lot of other manipulation on dendrograms with the <a rel="nofollow" href="https://cran.r-project.org/web/packages/dendextend/" target="_blank">dendextend</a> package such as – changing the color of labels, changing the size of text of labels, changing type of line of branches, its colors, etc. You can also change the label text as well as sort it. You can see the many options in the <a rel="nofollow" href="https://cran.r-project.org/web/packages/dendextend/vignettes/introduction.html" target="_blank">online vignette</a> of the package.</p>
<p>Another important function that the dendextend package offers is tanglegram. It is used to compare two dendrogram (with the same set of labels), one facing the other, and having their labels connected by lines. </p>
<p>As an example, let’s compare the single and complete linkage methods for agnes function.</p>
<pre>library(dendextend)

hc_single &lt;- agnes(data, method = &quot;single&quot;)
hc_complete &lt;- agnes(data, method = &quot;complete&quot;)

# converting to dendogram objects as dendextend works with dendogram objects 
hc_single &lt;- as.dendrogram(hc_single)
hc_complete &lt;- as.dendrogram(hc_complete)

tanglegram(hc_single,hc_complete)
</pre>
<p><img data-orig-file="https://i0.wp.com/r-posts.com/wp-content/uploads/2017/12/dendextend.png?fit=800%2C484" data-orig-size="800,484" data-medium-file="https://i0.wp.com/r-posts.com/wp-content/uploads/2017/12/dendextend.png?fit=450%2C272" data-attachment-id="388" data-image-meta="{" data-image-description="" src="https://i0.wp.com/r-posts.com/wp-content/uploads/2017/12/dendextend.png?resize=450%2C272" data-permalink="http://r-posts.com/how-to-perform-hierarchical-clustering-using-r/dendextend/" data-large-file="https://i0.wp.com/r-posts.com/wp-content/uploads/2017/12/dendextend.png?fit=450%2C272" alt="" data-image-title="dendextend" sizes="(max-width: 450px) 100vw, 450px" width="450" data-comments-opened="1" class="wp-image-388" data-recalc-dims="1" height="272"></p>
<p>This is useful in comparing two methods. As seen in the figure, one can relate to the methodology used for building the clusters by looking at this comparison.<br>
You can find more functionalities of the dendextend package <a rel="nofollow" href="https://cran.r-project.org/web/packages/dendextend/vignettes/introduction.html" target="_blank">here</a>.</p>
<h2>End Notes</h2>
<p>Hope now you have a better understanding of clustering algorithms than what you started with. We discussed about Divisive and Agglomerative clustering techniques and four linkage methods namely, Single, Complete, Average and Ward’s method. Next, we implemented the discussed techniques in R using a numeric dataset. Note that we didn’t have any categorical variable in the dataset we used. You need to treat the categorical variables in order to incorporate them into a clustering algorithm. Lastly, we discussed a couple of plots to visualise the clusters/groups formed. Note here that we have assumed value of ‘k’ (number of clusters) is known. However, this is not always the case. There are a number of heuristics and rules-of-thumb for picking number of clusters. A given heuristic will work better on some datasets than others. It’s best to take advantage of domain knowledge to help set the number of clusters, if that’s possible. Otherwise, try a variety of heuristics, and perhaps a few different values of k.</p>
<h2>Consolidated code</h2>
<pre>install.packages('cluster')
install.packages('purrr')
install.packages('factoextra')

library(cluster)
library(purrr)
library(factoextra)
data &lt;- car::Freedman
data &lt;- na.omit(data)
data &lt;- scale(data)

d &lt;- dist(data, method = &quot;euclidean&quot;)
hc1 &lt;- hclust(d, method = &quot;complete&quot; )

plot(hc1, cex = 0.6, hang = -1)

hc2 &lt;- agnes(data, method = &quot;complete&quot;)
hc2$ac

m &lt;- c( &quot;average&quot;, &quot;single&quot;, &quot;complete&quot;, &quot;ward&quot;)
names(m) &lt;- c( &quot;average&quot;, &quot;single&quot;, &quot;complete&quot;, &quot;ward&quot;)

ac &lt;- function(x) {
  agnes(data, method = x)$ac
}

map_dbl(m, ac)  

hc3 &lt;- agnes(data, method = &quot;ward&quot;)
pltree(hc3, cex = 0.6, hang = -1, main = &quot;Dendrogram of agnes&quot;)

hc4 &lt;- diana(data)
hc4$dc

pltree(hc4, cex = 0.6, hang = -1, main = &quot;Dendrogram of diana&quot;)

clust &lt;- cutree(hc4, k = 5)
fviz_cluster(list(data = data, cluster = clust))

pltree(hc4, hang=-1, cex = 0.6)
rect.hclust(hc4, k = 9, border = 2:10)

library(dendextend)

hc_single &lt;- agnes(data, method = &quot;single&quot;)
hc_complete &lt;- agnes(data, method = &quot;complete&quot;)

# converting to dendogram objects as dendextend works with dendogram objects 
hc_single &lt;- as.dendrogram(hc_single)
hc_complete &lt;- as.dendrogram(hc_complete)

tanglegram(hc_single,hc_complete)
</pre>
<h2>Author Bio:</h2>
<p>This article was contributed by <a rel="nofollow" href="http://www.perceptive-analytics.com/" target="_blank">Perceptive Analytics</a>. Amanpreet Singh, Chaitanya Sagar, Jyothirmayee Thondamallu and Saneesh Veetil contributed to this article. </p>
<p>Perceptive Analytics provides data analytics, business intelligence and reporting services to e-commerce, retail and pharmaceutical industries. Our client roster includes Fortune 500 and NYSE listed companies in the USA and India.</p>
	<p>
<div>
<div>To <strong>leave a comment</strong> for the author, please follow the link and comment on their blog: <strong><a href="http://r-posts.com/how-to-perform-hierarchical-clustering-using-r/"> R-posts.com</a></strong>.</div>
<hr>
<a rel="nofollow" href="https://www.r-bloggers.com/">R-bloggers.com</a> offers <strong><a rel="nofollow" href="https://feedburner.google.com/fb/a/mailverify?uri=RBloggers">daily e-mail updates</a></strong> about <a rel="nofollow" href="https://www.r-project.org/" title="The R Project for Statistical Computing">R</a> news and <a rel="nofollow" href="https://www.r-bloggers.com/search/tutorial" title="R tutorials">tutorials</a> on topics such as: <a rel="nofollow" href="https://www.r-bloggers.com/search/data%20science" title="Data science">Data science</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/Big%20Data" title="Big Data">Big Data, <a rel="nofollow" href="https://www.r-users.com/" title="R jobs">R jobs</a>, visualization (<a rel="nofollow" href="https://www.r-bloggers.com/search/ggplot2" title="ggplot and ggplot2 tutorials">ggplot2</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/boxplot" title="Boxplots using lattice and ggplot2 tutorials">Boxplots</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/map" title="Maps and gis">maps</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/animation" title="Animation in R">animation</a>), programming (<a rel="nofollow" href="https://www.r-bloggers.com/search/RStudio" title="RStudio IDE for R">RStudio</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/sweave" title="Sweave and literate programming">Sweave</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/LaTeX" title="LaTeX in R">LaTeX</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/SQL" title="SQL and databases">SQL</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/eclipse" title="Eclipse IDE for R">Eclipse</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/git" title="git and github, Version Control System">git</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/hadoop" title="Large data in R using Hadoop">hadoop</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/Web+Scraping" title="Web Scraping of google, facebook, yahoo, twitter and more using R">Web Scraping</a>) statistics (<a rel="nofollow" href="https://www.r-bloggers.com/search/regression" title="Regressions and ANOVA analysis tutorials">regression</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/PCA" title="principal component analysis tutorial">PCA</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/time+series" title="Time series">time series</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/trading" title="finance trading">trading</a>) and more...
<img alt="" width="1" src="http://feeds.feedburner.com/~r/RBloggers/~4/LQLJ2ZsyNcY" height="1"></a></div>