![]() |
| See Video ⮞ ☝ |
AGRON stats
January 25, 2020
Introduction
Clustering groups observations according to a chosen measure of dissimilarity. The resulting groups depend on feature selection, preprocessing, distance definition, and clustering algorithm; they are not automatically objective or naturally occurring categories.
Packages used
This tutorial uses cluster for distance calculations and factoextra for visualization. Install packages from a trusted repository as needed, and note their versions when reproducibility is important.
install.packages("cluster")
install.packages("factoextra")
# OR install both packages with single command
install.packages(c("cluster", "factoextra"))Load the required packages once per R session. In scripts, library() is commonly used to attach a package; require() returns a logical value and can be useful in conditional code.
Use .packages(all = TRUE) to obtain just the names of all available packages
Import data file
Prepare the data before importing it: identify numeric features, categorical variables, identifiers, and any missing values. Preserve labels separately from the feature matrix used to calculate distances.
- Use first row as
column namesthat represent variables - Use first column as
row namesthat represent observations - Avoid column names with
blank spaces. For example, good name for plant height is to place underscore or dot between the two words e.gplant_heightorplant.height. A bad name for plant height is to give space between the two words (plant height). - Avoid name with
special symbols. - Avoid beginning variable names with a number. Use letter instead e.g instead of 1000_grain_weight type
th_grain_weightorgrain_weight_1000. - Avoid
blank rowsin your data - Delete any
commentsin your file - Replace
missing valueswith NA usingna.omit()function - Use four digit format for column containing date
Save the prepared file as CSV or load a built-in data set with data(). This example uses USArrests; inspect its documentation and rows before selecting variables.
# Murder Assault UrbanPop Rape
# Alabama 13.2 236 58 21.2
# Alaska 10.0 263 48 44.5
# Arizona 8.1 294 80 31.0
# Arkansas 8.8 190 50 19.5
# California 9.0 276 91 40.6
# Colorado 7.9 204 78 38.7
Handling with missing values
Use na.fail() to detect incomplete data, or identify missingness explicitly. na.omit() removes incomplete rows and may change the sample or bias results if missingness is systematic; report exclusions and consider a justified alternative.
na.pas() function returns the object unchanged
Scaling of the data
Scaling affects distances and therefore can change cluster structure. Standardize variables when their units or ranges would otherwise dominate, or retain original scales when their magnitudes are scientifically meaningful and intended to receive greater weight.
Generally variables are scaled to have one value for standard deviation and zero value for mean.
The base R scale() function centers columns and, when requested, divides by their standard deviations. Other robust transformations are possible, but they are not performed by scale() itself.
Apply scaling consistently to the numeric features selected for analysis. Check the transformed values and document the chosen center and scale.
# Murder Assault UrbanPop Rape
# Alabama 1.24256408 0.7828393 -0.5209066 -0.003416473
# Alaska 0.50786248 1.1068225 -1.2117642 2.484202941
# Arizona 0.07163341 1.4788032 0.9989801 1.042878388
# Arkansas 0.23234938 0.2308680 -1.0735927 -0.184916602
# California 0.27826823 1.2628144 1.7589234 2.067820292
# Colorado 0.02571456 0.3988593 0.8608085 1.864967207
Distance matrix computation
Common distance choices include Euclidean, Manhattan, Canberra, and other measures. Select a distance that fits the variable types and scientific interpretation.
- Euclidean distance
- correlation based distance
- distance for mixed data
Euclidean distance
The dist() function computes distances between rows of a numeric matrix. The resulting values are sensitive to feature scales, so decide on preprocessing before choosing the distance measure.
method: “euclidean”, “maximum”, “manhattan”, “canberra”, “binary” or “minkowski”
Convert the compact distance object to a matrix only when you need a square display for inspection. Round values for display, but retain the unrounded distances for any subsequent analysis.
# Alabama Alaska Arizona
# Alabama 0.0 2.7 2.3
# Alaska 2.7 0.0 2.7
# Arizona 2.3 2.7 0.0
The diagonal of a distance matrix is zero because each observation has zero distance from itself. Off-diagonal entries describe pairwise dissimilarity under the selected metric.
Correlation based distance
Correlation-based dissimilarities compare profiles by their association rather than their absolute magnitudes. They are useful for some profile analyses, but the exact transformation from correlation to distance should be checked and documented.
The method argument selects a correlation measure, such as Pearson, Spearman, or Kendall. Choose based on whether linear or rank-based monotonic association is meaningful for the data.
Pearson correlation measures linear association, whereas Spearman and Kendall use ranks. Their use does not eliminate the need to inspect outliers, ties, or the shape of the relationships.
library(factoextra)
data.cor <- get_dist(x = data.scaled,
method = "pearson")
round(as.matrix(data.cor)[1:3, 1:3], 1)# Alabama Alaska Arizona
# Alabama 0.0 0.7 1.4
# Alaska 0.7 0.0 0.8
# Arizona 1.4 0.8 0.0
Distances for mixed data
For mixed numeric and categorical data, cluster::daisy() can calculate Gower dissimilarities. Confirm variable types, ordered-factor coding, weights, and handling of missing values before interpreting the result.
The flower example contains numeric and categorical variables. Inspect and set each variable’s class correctly, because distance calculations depend on whether a column is numeric, nominal, or ordinal.
# 'data.frame': 18 obs. of 8 variables:
# $ V1: Factor w/ 2 levels "0","1": 1 2 1 1 1 1 1 1 2 2 ...
# $ V2: Factor w/ 2 levels "0","1": 2 1 2 1 2 2 1 1 2 2 ...
# $ V3: Factor w/ 2 levels "0","1": 2 1 1 2 1 1 1 2 1 1 ...
# $ V4: Factor w/ 5 levels "1","2","3","4",..: 4 2 3 4 5 4 4 2 3 5 ...
# $ V5: Ord.factor w/ 3 levels "1"<"2"<"3": 3 1 3 2 2 3 3 2 1 2 ...
# $ V6: Ord.factor w/ 18 levels "1"<"2"<"3"<"4"<..: 15 3 1 16 2 12 13 7 4 14 ...
# $ V7: num 25 150 150 125 20 50 40 100 25 100 ...
# $ V8: num 15 50 50 50 15 40 20 15 15 60 ...
Use daisy() with the prepared mixed-type data frame and appropriate settings. Inspect the returned dissimilarities and verify that no identifier or unintended column is included.
# 1 2 3
# 1 0.00 0.89 0.53
# 2 0.89 0.00 0.51
# 3 0.53 0.51 0.00
Visualizing distances
Visualize the distance matrix with factoextra::fviz_dist() to inspect patterns of pairwise dissimilarity. A distance plot is not a cluster assignment; choose and fit a clustering method separately, then evaluate the resulting groups.
This function classify data samples into groups of similar objects.
library(factoextra)
# Visualize Euclidean matrix
fviz_dist(dist.obj = data.eucl,
order = TRUE, show_labels = TRUE)
# Visualize correlation matrix
fviz_dist(dist.obj = data.cor,
order = TRUE, show_labels = TRUE)
# Visualize mixed data distance matrix
fviz_dist(dist.obj = data.daisy,
order = TRUE, show_labels = TRUE)

Comments
Post a Comment