Rmd

Clustering Prinzipien

Agglomerative Hierarchical Clustering

Alle Personen werden nach einem Distanzmaß successive zu Clustern zusammengefasst, bis alle Personen in einem einzigen Cluster sind. Auf einem bestimmten Niveau kann man die Zuordnung der Personen zu den Clustern interpretieren. Hierbei spielen die Unterschiede im Distanzmaß zwischen den Clustern eine Rolle. Eine Visualisierung mithilfe eines Dentrogramms hilft hierbei.

k-Means Clustering

Die Beobachtungen sollen einer fest vorgegebenen Anzahl von Clustern zugeordnet werden. Kriterium der besten Lösung kann z. B. das Minimieren der Binnenvarianz der resultierenden Cluster sein (within group sum of squares). Problem: Die Lösung ist abhängig von der Skalierung der Variablen (s.u. ) Problem: Systematisches Permutieren aller Personen-Cluster-Kombinationen wächst exponentiell.

Model-Based Clustering.

Über Maximum Likelihood Schätzungen wird ein möglichst gut an die Daten angepasstes Modell ermittelt.

Euclidean Distance

\[ d_{ij} = \sqrt{\sum_{k=1}^{q}{(x_{ik} - x_{jk})^2}} \] i, j: individuals \ variables: \(x_{j1}, x_{j2}, ..., x_{jq}\)

dist()

dist() erzeugt eine Distanzmatrix.

Default Euklidische Distanz. Quadrierte Differenz zwischen je zwei Vpn in einer Variable, über die Variablen summiert und daraus die Wurzel ist die euklidische Distanz zwischen diesen beiden Vpn.

Da verschiedene Variablen, nach denen geclustert wird, je nach Skalierung unterschiedlich hoch in das Distanzmaß eingehen, kann es sinnvoll sein, die Maße vorher zu normieren (z-transformieren). scale() dient hierzu.

hclust()

hclust() clustert hclust(dmat, method = “complete”)

methods:

  • single: the smallest distance between the objects being clustered
  • complete: the largest distance between the objects being clustered
  • average: the average distance between the objects being clustered

Dendrogramm mit plot()

Ein Dendrogramm erstellt man, indem man plot() auf ein hclust()-Objekt aufruft.

Zugehörigkeit zu Clustern: cutree()

cutree() wird auf ein hclust()-Objekt angewendet und erzeugt einen Vektor mit der Zugehörigkeit der Beobachtungen zu den Clustern.

Parameter h: ‘Schneidet’ das Dendrogramm auf dieser Höhe auf. Parameter k: Teilt die Stichprobe in k Gruppen/Cluster auf, wählt also die zugehörige Höhe.

plot(hclust())

Plottet eine Clusteranalyse vom Typ hclust.

kmeans()

Vorgegebene Anzahl von Clustern: kmeans()

Bei vorgegebener Anzahl von Clustern werden die Beobachtungen so aufgeteilt, dass die Distanzen innerhalb der Gruppen minimiert werden.

kmeans(x, n) x ist Datenmatrix n ist Anzahl der Cluster

Beispiele aus Everitt (2010)

Beispiel: Body Data (Everitt, 2010)

Körpermaße: Brust, Bauch, Hüfte von 20 Vpn.

d.body <- read.delim(file="http://md.psych.bio.uni-goettingen.de/mv/data/div/mv_body.txt")
# zeige DataFrame
head(d.body)
##   Chest Waist Hips
## 1    34    30   32
## 2    37    32   37
## 3    38    30   36
## 4    36    33   39
## 5    38    29   33
## 6    43    32   38
attach(d.body)
#
options(digits=3)

# eine Matrix der euklidischen Distanzen erzeugen
distances<-dist(d.body)

# Agglomerativer Algorithmus
h.body <- hclust(distances,method="single")
print(hclust(distances,method="single"))
## 
## Call:
## hclust(d = distances, method = "single")
## 
## Cluster method   : single 
## Distance         : euclidean 
## Number of objects: 20
# was gibt es alles im Ergebnisobjekt?
str(hclust(distances,method="single"))
## List of 7
##  $ merge      : int [1:19, 1:2] -12 -15 -16 -11 -13 -8 -3 -6 3 5 ...
##  $ height     : num [1:19] 1 1 1 1.41 1.41 ...
##  $ order      : int [1:20] 1 7 5 6 10 4 2 3 9 8 ...
##  $ labels     : NULL
##  $ method     : chr "single"
##  $ call       : language hclust(d = distances, method = "single")
##  $ dist.method: chr "euclidean"
##  - attr(*, "class")= chr "hclust"
# Dendrogramm
plot(hclust(distances,method="single"))

# Zuordnung der Vpn zu Clustern, entweder in Abhängigkeit von der Höhe
# oder mit Vorgabe der Menge der Cluster

body_sl3<-cutree(hclust(distances,method="single"),h=3.8)
body_sl3
##  [1] 1 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2
# alternativ mit Angabe der Cluster
body_sl3<-cutree(hclust(distances,method="single"),k=2)
body_sl3
##  [1] 1 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2
# Die unterschiedlichen Distanzmaße erzeugen durchaus verschiedene Cluster
body_cl2<-cutree(hclust(distances,method="complete"),h=10)
#
body_al2<-cutree(hclust(distances,method="average"),h=7.8)

# eine vergleichende Darstellung der Clusterung über verschiedene Clustering-Methoden
## layout(matrix(c(1,2,3,4,5,6),2,3,byrow=TRUE),c(1,1,1),c(2,1),TRUE)
# plclust(hclust(distances, method="single"),  ylab="Height", sub="Single linkage")
# plclust(hclust(distances, method="complete"),ylab="Height", sub="Complete linkage")
# plclust(hclust(distances, method="average"), ylab="Height", sub="Average linkage")
plot(hclust(distances, method="single"),  ylab="Height", sub="Single linkage")

plot(hclust(distances, method="complete"),ylab="Height", sub="Complete linkage")

plot(hclust(distances, method="average"), ylab="Height", sub="Average linkage")

# als Darstellungsidee: Plot der beiden principal Components in einem Scatterplot
# die Cluster-Zuordnung kommt aus dem cutree() Befehl

# PCA rechnen und speichern
pc.body<-princomp(d.body,cor=T)

# Plot der Vp-Scores der ersten beiden PCA-Komponenten
# Achsenbereich festlegen
xlim<-range(pc.body$scores[,1])

# Grafik aufmachen
plot(pc.body$scores[,1:2], type="n", xlim=xlim, ylim=xlim)

plot(pc.body$scores[,1:2], type="n")

# An Stelle von Punkten Buchstaben (Clusterzugehörigkeit) an die Koordinaten schreiben 
##text(pc.body$scores[,1:2], labels=body_sl3, cex=0.6)
# dito für comlete-linkage
plot(pc.body$scores[,1:2], type="n", xlim=xlim, ylim=xlim)
text(pc.body$scores[,1:2], labels=body_cl2, cex=0.6)

# dito für average-linkage
plot(pc.body$scores[,1:2], type="n", xlim=xlim, ylim=xlim)
text(pc.body$scores[,1:2], labels=body_al2, cex=0.6)

# Einzelgrafik: Zwei principal components plot der 3-Cluster-Lösung mit complete-linkage
##par(mfrow=c(1,1))
##jpeg(file="cl-body-detail.jpg")
c.3    <- hclust(distances, method="complete")
c.3.vp <- cutree(c.3, k=3)
pc<-princomp(d.body,cor=T)
xlim<-range(pc$scores[,1])
plot(pc$scores[,1:2], type="n", xlim=xlim, ylim=xlim)
text(pc$scores[,1:2], labels=c.3.vp, cex=0.8)

##par(mfrow=c(1,1))
library(tidyverse)
## ── Attaching packages ─────────────────────────────────────── tidyverse 1.3.1 ──
## ✔ ggplot2 3.3.5     ✔ purrr   0.3.4
## ✔ tibble  3.1.6     ✔ dplyr   1.0.8
## ✔ tidyr   1.2.0     ✔ stringr 1.4.0
## ✔ readr   2.1.2     ✔ forcats 0.5.1
## ── Conflicts ────────────────────────────────────────── tidyverse_conflicts() ──
## ✖ dplyr::filter() masks stats::filter()
## ✖ dplyr::lag()    masks stats::lag()

dd.t <- data.frame(cbind(pc$scores, body_cl2))
dd.t$body_cl2.f <- factor(dd.t$body_cl2)
dd.t %>% ggplot(aes(x=Comp.1, y=Comp.2, group=body_cl2.f, color=body_cl2.f)) +
  geom_point()

# d.body wieder aus Namespace nehmen
detach(d.body)

Beispiel Lebenserwartung (Everitt, 2010)

Daten von Keyfitz & Flieger (1971). Lebenserwartung nach Geschlecht und Alter getrennt für eine Menge von Ländern (insgesamt 27).

Varianzen:

Birth variance = 66.08
Aged 25 variance = 25.26
Aged 50 variance = 13.07
Aged 75 variance = 4.56

Wegen der sehr unterschiedlichen Varianzen bietet sich Standardisierung der Daten an, um die euklidischen Distanzen nicht zu verzerren.

d.life <- read.delim(file="http://md.psych.bio.uni-goettingen.de/mv/data/div/cl-life.txt")

#standardisieren - aber nur die Standardabweichungen (auf 1), die Mittelwerte bleiben.
sds<-apply(d.life[,2:5], 2, sd)
d.st.life <- sweep(as.matrix(d.life[,2:5]),2,sds,FUN="/")
# und zeigen
d.st.life
##         m0   m25  m50  m75
##  [1,] 7.75 10.15 8.30 6.09
##  [2,] 4.18  5.77 3.60 2.34
##  [3,] 4.67  5.97 4.70 3.28
##  [4,] 7.26  8.36 5.53 2.81
##  [5,] 6.89  7.56 4.98 3.28
##  [6,] 7.63  8.75 6.64 3.28
##  [7,] 6.15  7.76 5.53 3.28
##  [8,] 8.00  8.75 6.09 3.28
##  [9,] 6.89  9.15 6.64 5.15
## [10,] 8.49  9.35 6.64 3.75
## [11,] 8.00  9.55 7.19 4.22
## [12,] 7.87  9.95 7.74 5.15
## [13,] 6.89  8.75 6.91 4.68
## [14,] 7.38  8.75 6.09 2.81
## [15,] 7.50  8.95 6.09 3.75
## [16,] 6.03  7.96 6.09 4.22
## [17,] 7.26  8.36 6.09 2.81
## [18,] 7.75  8.75 6.36 3.75
## [19,] 7.26  8.75 6.64 3.75
## [20,] 8.00  9.55 7.74 6.56
## [21,] 8.00  9.55 7.19 4.22
## [22,] 7.87  8.56 5.81 2.81
## [23,] 8.24  8.95 6.36 3.75
## [24,] 8.00  9.15 6.64 4.22
## [25,] 7.26  8.56 6.36 4.68
## [26,] 7.13  8.75 6.64 4.22
## [27,] 7.01  9.15 7.74 4.22
options(digits=3)

#get distance matrix
distances<-dist(d.st.life)
#

#figure 12.6
# nicht unterteiltes Grafikfenster
par(mfrow=c(1,1))
labs <- d.life$country
plot(hclust(distances,method="complete"),ylab="Height",sub="Complete linkage",labels=labs)

# nähere Untersuchung der 4-Cluster Lösung
#pick up 4 group solution
life_cl4<-cutree(hclust(distances,method="complete"),h=3)

#fig 12.7
pairs(d.life[,2:5],panel=function(x,y) text(x,y,labels=life_cl4,cex=0.6))

#Fig 12.8
pc.life <- princomp(d.st.life,cor=T)
xlim <- range(pc.life$scores[,1])
plot(pc.life$scores[,1:2], type="n", xlim=xlim, ylim=xlim)
text(pc.life$scores[,1:2], labels=life_cl4, cex=0.8)

#means and membership of four clusters
# Mittelwerte für die Cluster
country.mean <- lapply(1:4, function(nc) apply(d.life[life_cl4==nc,2:5],2,mean))
country.mean
## [[1]]
##   m0  m25  m50  m75 
## 64.0 49.7 28.7 12.7 
## 
## [[2]]
##   m0  m25  m50  m75 
## 36.0 29.5 15.0  6.0 
## 
## [[3]]
##    m0   m25   m50   m75 
## 57.75 41.50 20.88  6.75 
## 
## [[4]]
##    m0   m25   m50   m75 
## 61.57 45.29 24.29  8.79
# die zu den Clustern gehörenden Länder heraussuchen
# ?? noch anpassen
country.clus <- lapply(1:4, function(nc) d.life$country[life_cl4==nc])
country.clus
## [[1]]
## [1] "Algeria"       "Dominican Rep" "Nicaragua"    
## 
## [[2]]
## [1] "Cameroon"   "Madagascar"
## 
## [[3]]
## [1] "Mauritius"       "Reunion"         "South Africa(C)" "South Africa(W)"
## [5] "Greenland"       "Guatemala"       "Honduras"        "Trinidad (67)"  
## 
## [[4]]
##  [1] "Seychelles"         "Tunisia"            "Canada"            
##  [4] "Costa Rica"         "El Salvador"        "Grenada"           
##  [7] "Jamaica"            "Mexico"             "Panama"            
## [10] "United States (67)" "Argentina"          "Chile"             
## [13] "Columbia"           "Ecuador"
#

Beispiel: Kriminalitätsdaten (Everitt, 2010)

Im Beispiel Kriminalitätsdaten USA geht es um eine vorgegebene Anzahl von Clustern und der Anwendung des Befehls kmeans().

Crime Rates. Quelle: The Statistical Abstract of the USA (1988).

Rates of different types of crime per 100.000 residents.

  • murder (Mord)
  • rape (Vergewaltigung)
  • robbery (Raubüberfall)
  • assault (Überfall (mit Körperverletzung?))
  • burglery (Einbruch)
  • theft (Diebstahl)
# k-means
#crime rate data
#d.crime<-source("c:\\mvmvbs\\chap102_dat.txt")$value
# Daten einlesen
d.crime <- read.delim(file="http://md.psych.bio.uni-goettingen.de/mv/data/div/pca_crime.txt")

head(d.crime)
##   state murder rape robbery assault burglary theft vehicules
## 1    ME    2.0 14.8      28     102      803  2347       164
## 2    NH    2.2 21.5      24      92      755  2208       228
## 3    VT    2.0 21.8      22     103      949  2697       181
## 4    MA    3.6 29.7     193     331     1071  2189       906
## 5    RI    3.5 21.4     119     192     1294  2568       705
## 6    CT    4.6 23.8     192     205     1198  2758       447
#remove DC (ist Ausreisser)
d.crime<-d.crime[-24,]
#rlabs<-row.names(d.crime)
rlabs <- d.crime[,1]

# Varianzen ansehen
apply(d.crime[2:8],2,var)
##    murder      rape   robbery   assault  burglary     theft vehicules 
##      11.9     209.8   11889.6   19373.5  175895.0  565276.6   43997.4
# die sind sehr hoch
# standardize by range
# Ranges ermitteln und speichern
rge <- apply(d.crime[2:8], 2, max) - apply(d.crime[2:8],2,min)
# Standardisieren indem durch Range geteilt wird
crime_std <- sweep(d.crime[2:8], 2, rge, FUN="/")
# Standardisierte Streuungen ansehen
apply(crime_std,2,var)
##    murder      rape   robbery   assault  burglary     theft vehicules 
##    0.0764    0.0562    0.0463    0.0590    0.0522    0.0622    0.0676
# WGSS ermitteln
# within group sum of squares
# Inner-Gruppen-Quadratsumme(n) über die Anzahl der Gruppen
# bei nur einer Gruppe die Varianz in der Gruppe
#plot of wgss against number of clusters
n <- length(crime_std[,1])
# Summe der Varianzen über die Variablen * n-1
wss1 <- (n-1) * sum(apply(crime_std, 2, var))
# einen leeren Vektor aufmachen
wss <- numeric(0)
# und füllen
for(i in 2:6) {
    W <- sum(kmeans(crime_std, i)$withinss)
    wss<-c(wss, W)
}

# wss1 vorne dran hängen
wss<-c(wss1,wss)
# wss enthält jetzt 6 Werte, die Innergruppen-Quadratsummen

# jetzt plotten
plot(1:6, wss, type="l", xlab="Number of groups", ylab="Within groups sum of squares", lwd=2)

#get two-group solution from k-means and group means and membership
# das Modell rechnen und speichern
crime_kmean2 <- kmeans(crime_std, 2)

# nur die Variablen in einem Datenobjekt speichern
crime <- d.crime[2:8]
# Ausgabe der Mittelwerte unstandardisiert (zum besseren Vergleich)
lapply(1:2, function(nc) apply(crime[crime_kmean2$cluster == nc,], 2, mean))
## [[1]]
##    murder      rape   robbery   assault  burglary     theft vehicules 
##      9.37     45.37    229.00    394.77   1543.41   3368.05    554.27 
## 
## [[2]]
##    murder      rape   robbery   assault  burglary     theft vehicules 
##      4.74     24.80     73.82    182.07    924.21   2564.71    247.04
# Ausgabe der zum Cluster gehörigen Bundesstaaten
# die Werte im Cluster 1 sind deutlich niedriger, als im Cluster 2
lapply(1:2, function(nc) rlabs[crime_kmean2$cluster==nc])
## [[1]]
##  [1] "MA" "NY" "NJ" "IL" "MI" "MO" "MD" "SC" "GA" "FL" "TN" "LA" "OK" "TX" "CO"
## [16] "NM" "AZ" "NV" "WA" "OR" "CA" "AK"
## 
## [[2]]
##  [1] "ME" "NH" "VT" "RI" "CT" "PA" "OH" "IN" "WI" "MN" "IA" "ND" "SD" "NE" "KS"
## [16] "DE" "VA" "WV" "NC" "KY" "AL" "MS" "AR" "MT" "ID" "WY" "UT" "HI"
# lapply(x, function() ...)
# wendet die function() auf alle Elemente x an
# gibt entsprechend lange Liste von Ergebnissen zurück
# function() ist frei definierbar
# function(nc) übergibt als Paramter nc je ein Element von x, führt function(nc) aus 
# und speichert das Ergebnis in Ergebnisvektor

Beispiel: Gastroenterologen (Everitt, 2010)

Beurteilt wird die Offenheit von Gastroenterologen in verschiedenen Ländern. Angewendet wird Maximum Likelihood Clustering

Model-Based Clustering: funktioniert auch noch gut bei überlappenden Clustern, wo k-means und agglomeratives Clustern Schwierigkeiten haben. BIC = Basean Information Criterion.

Wie offen sind Gastroenterologen, wenn sie bei einem Patienten Krebs festgestellt haben. Daten von 600 Gastroenterologen aus 27 europäischen Ländern. Ja/Nein (Anteil der Ja).

Q1: Would you tell this patient that he or she has cancer if he or she asks no questions?
Q2: Would you tell the wife or husband that the patient has cancer?
Q3: Would you tell the patient that he or she has a cancer if he or she directly asks you to disclose the diagnosis?
(During surgery, the surgeon notices several small metastases in the liver)
Q4: Would you tell the patient about the metastases (supposing the patient asks to be told the results of the operation)?
Q5: Would you tell the patient that th condition is incurable?
Q6: Would you tell the wife or husband that the operation revealed metastases?
d.gastroent <- read.delim(file="http://md.psych.bio.uni-goettingen.de/mv/data/div/cl-gastroent.txt")

#library(mclust02)
library(mclust)
## Package 'mclust' version 5.4.10
## Type 'citation("mclust")' for citing this R package in publications.
## 
## Attache Paket: 'mclust'
## Das folgende Objekt ist maskiert 'package:purrr':
## 
##     map
d.gast <- d.gastroent[2:7]

# das beste Modell finden
c.res<-Mclust(d.gast)

# das beste Modell ausgeben
# hier ist das Basean Information Criterion (BIC) am höchsten
c.res
## 'Mclust' model object: (VEV,4) 
## 
## Available components: 
##  [1] "call"           "data"           "modelName"      "n"             
##  [5] "d"              "G"              "BIC"            "loglik"        
##  [9] "df"             "bic"            "icl"            "hypvol"        
## [13] "parameters"     "z"              "classification" "uncertainty"
# die BIC ansehen
c.res$BIC
## Bayesian Information Criterion (BIC): 
##       EII    VII     EEI    VEI   EVI   VVI     EEE   VEE   EVE   VVE    EEV
## 1 -107.95 -108.0 -73.543 -73.54 -73.5 -73.5  -9.206 -9.21 -9.21 -9.21  -9.21
## 2  -26.78  -29.0 -17.250   2.85  12.3  21.9  -6.214 11.91  6.83 43.85   4.28
## 3   -5.41   16.6 -11.219  17.02    NA    NA -17.312    NA    NA    NA -12.94
## 4   11.93   25.8   1.980  17.26    NA    NA -31.230    NA    NA    NA     NA
## 5   23.26   17.0  -0.287  15.25    NA    NA -27.749    NA    NA    NA     NA
## 6    4.21     NA -14.251     NA    NA    NA -12.493    NA    NA    NA     NA
## 7    8.38     NA  15.421     NA    NA    NA   5.562    NA    NA    NA     NA
## 8  -12.51     NA   0.150     NA    NA    NA  -0.867    NA    NA    NA     NA
## 9  -26.21     NA  -1.167     NA    NA    NA -15.766    NA    NA    NA     NA
##      VEV   EVV   VVV
## 1  -9.21 -9.21 -9.21
## 2  46.90 -4.99 43.14
## 3  25.93    NA    NA
## 4 151.06    NA    NA
## 5     NA    NA    NA
## 6     NA    NA    NA
## 7     NA    NA    NA
## 8     NA    NA    NA
## 9     NA    NA    NA
## 
## Top 3 models based on the BIC criterion: 
## VEV,4 VEV,2 VVE,2 
## 151.1  46.9  43.8
# der höchste steht in 
c.res$bic
## [1] 151
# die Plots dazu
#plot(c.res,d.gast)
plot(c.res)

was bedeuten die Abkürzungen?

aus der Hilfe:

  ?mclustModelNames
  
  univariateMixture
  A vector with the following components: 
  "E": equal variance (one-dimensional) 
  "V": variable variance (one-dimensional)
  multivariateMixture
  A vector with the following components: 
  "EII": spherical, equal volume 
  "VII": spherical, unequal volume 
  "EEI": diagonal, equal volume and shape
  "VEI": diagonal, varying volume, equal shape
  "EVI": diagonal, equal volume, varying shape 
  "VVI": diagonal, varying volume and shape 
  "EEE": ellipsoidal, equal volume, shape, and orientation 
  "EEV": ellipsoidal, equal volume and equal shape
  "VEV": ellipsoidal, equal shape 
  "VVV": ellipsoidal, varying volume, shape, and orientation
  singleComponent
  A vector with the following components: 
  "X": one-dimensional 
  "XII": spherical 
  "XXI": diagonal 
  "XXX": ellipsoidal
# Die Mittelwerte der Fragen (Zustimmung zu Frage) in den vier Clustern
c.res$parameters$mean
##     [,1]  [,2]   [,3]   [,4]
## q1 0.872 0.798 0.2468 0.0429
## q2 0.931 0.779 1.0000 0.9617
## q3 1.000 0.811 0.7941 0.2357
## q4 0.956 0.563 0.2921 0.0640
## q5 0.810 0.306 0.0167 0.0204
## q6 0.919 0.746 1.0000 0.9542
countries <- d.gastroent[,1]
#countries in each class
countries[c.res$classification==1]
## [1] "Iceland"     "Norway"      "UK"          "Netherlands"
countries[c.res$classification==2]
## [1] "Sweden"         "Finland"        "Denmark"        "Ireland"       
## [5] "Germany"        "Switzerland"    "Albania"        "Czechoslovakia"
countries[c.res$classification==3]
## [1] "Belgium"    "Spain"      "Portugal"   "Italy"      "Greece"    
## [6] "Yugoslavia" "Hungary"    "Estonia"
countries[c.res$classification==4]
## [1] "France"    "Bulgaria"  "Romania"   "Poland"    "Russia"    "Lithuania"
## [7] "Latvia"
# der Klassifizierungsvektor
c.res$classification
##  [1] 1 1 2 2 2 1 2 2 1 3 2 4 3 3 3 3 3 2 4 4 3 2 4 4 4 4 3
# und jetzt auch hier Detailabbildung
# mit den ersten beiden PCA-Komponenten und den Clusternummern 

par(mfrow=c(1,1))
c.4.vp <- c.res$classification
pc <- princomp(d.gast, corr=T)
## Warning: In princomp.default(d.gast, corr = T) :
##  zusätzliches Argument 'corr' wird verworfen
xlim<-range(pc$scores[,1])
plot(pc$scores[,1:2], type="n", xlim=xlim, ylim=xlim)
text(pc$scores[,1:2], labels=c.4.vp, cex=0.8)

Weitere Beispiele, Übungen / Exercises

An Example from QuantDev

Quelle

#general packages
library(ggplot2)
library(psych)
## 
## Attache Paket: 'psych'
## Das folgende Objekt ist maskiert 'package:mclust':
## 
##     sim
## Die folgenden Objekte sind maskiert von 'package:ggplot2':
## 
##     %+%, alpha
#cluster packages
library(cluster) #clustering
library(fpc) #flexible procedures for clustering
library(clusterCrit) #cluster criteria

#set filepath for data file
filepath <- "https://quantdev.ssri.psu.edu/sites/qdev/files/AMIBbrief_raw_daily1.csv"

#read in the .csv file using the url() function
daily <- read.csv(file=url(filepath),header=TRUE)

#clean-up of variable names
var.names.daily <- tolower(colnames(daily))
colnames(daily)<-var.names.daily

#creating a new "id" variable
daily$id <- daily$id*10+daily$day

names(daily)
##  [1] "id"      "day"     "date"    "slphrs"  "weath"   "lteq"    "pss"    
##  [8] "se"      "swls"    "evalday" "posaff"  "negaff"  "temp"    "hum"    
## [15] "wind"    "bar"     "prec"
#reducing down to variable set
daily <- daily[ ,c("id","slphrs","weath","lteq","pss","se","swls","evalday", "posaff","negaff","temp","hum","wind","bar","prec")]

#names of variables
names(daily)
##  [1] "id"      "slphrs"  "weath"   "lteq"    "pss"     "se"      "swls"   
##  [8] "evalday" "posaff"  "negaff"  "temp"    "hum"     "wind"    "bar"    
## [15] "prec"
#looking at data    
head(daily,10)
##      id slphrs weath lteq  pss se swls evalday posaff negaff temp  hum wind
## 1  1010    6.0     1   10 2.50  2  3.8       1    3.9    3.0 28.0 0.79 11.0
## 2  1011    2.0     2   10 2.75  3  4.2       0    3.8    2.3 20.8 0.62  3.6
## 3  1012    9.0     3   10 3.50  4  5.0       1    5.1    1.0 29.1 0.51  1.9
## 4  1013    7.5     2    9 3.00  4  5.0       1    5.6    1.3 30.2 0.58  2.7
## 5  1014    8.0     1   18 2.75  3  4.0       1    4.3    1.1 22.7 0.55  2.4
## 6  1015    8.0     2   19 2.75  3  4.2       1    3.9    1.0 21.4 0.54  0.7
## 7  1016    8.0     3   21 3.50  4  4.6       1    5.1    1.2 31.4 0.49  1.0
## 8  1017    7.0    NA   14 2.75  3  4.6       1    4.8    1.1 45.3 0.52  1.1
## 9  1020    7.0     0   12 3.50  5  5.6       0    6.3    1.4 28.0 0.79 11.0
## 10 1021    6.0     0   20 4.00  5  6.6       0    7.0    1.6 20.8 0.62  3.6
##     bar prec
## 1  29.4 0.20
## 2  30.2 0.00
## 3  30.4 0.02
## 4  30.2 0.00
## 5  30.5 0.00
## 6  30.5 0.00
## 7  30.5 0.00
## 8  30.3 0.00
## 9  29.4 0.20
## 10 30.2 0.00
#removing observations with NA
dailysub <- daily[complete.cases(daily), ] 
describe(dailysub)
##         vars    n    mean      sd  median trimmed     mad     min    max
## id         1 1376 3276.28 1279.88 3271.50 3302.24 1497.43 1010.00 5327.0
## slphrs     2 1376    7.20    1.81    7.00    7.20    1.48    0.00   18.0
## weath      3 1376    2.00    1.29    2.00    2.00    1.48    0.00    4.0
## lteq       4 1376   12.50   10.42    9.00   11.24    8.90    0.00   58.0
## pss        5 1376    2.62    0.68    2.75    2.64    0.74    0.00    4.0
## se         6 1376    3.43    0.99    3.00    3.46    1.48    1.00    5.0
## swls       7 1376    4.11    1.27    4.20    4.15    1.19    1.00    7.0
## evalday    8 1376    0.68    0.46    1.00    0.73    0.00    0.00    1.0
## posaff     9 1376    4.11    1.10    4.20    4.14    1.19    1.00    7.0
## negaff    10 1376    2.45    1.04    2.20    2.34    1.04    1.00    6.9
## temp      11 1376   40.18    7.88   42.00   40.51    8.90   20.80   56.0
## hum       12 1376    0.62    0.20    0.66    0.63    0.21    0.24    0.9
## wind      13 1376    7.36    4.45    7.00    6.81    4.45    0.70   20.0
## bar       14 1376   30.02    0.33   30.00   30.04    0.43   29.32   30.5
## prec      15 1376    0.05    0.09    0.00    0.03    0.00    0.00    0.3
##           range  skew kurtosis    se
## id      4317.00 -0.10    -1.04 34.50
## slphrs    18.00  0.12     1.93  0.05
## weath      4.00 -0.06    -1.06  0.03
## lteq      58.00  1.07     0.95  0.28
## pss        4.00 -0.37     0.17  0.02
## se         4.00 -0.40    -0.12  0.03
## swls       6.00 -0.28    -0.22  0.03
## evalday    1.00 -0.79    -1.37  0.01
## posaff     6.00 -0.24    -0.37  0.03
## negaff     5.90  0.95     0.67  0.03
## temp      35.20 -0.37    -0.24  0.21
## hum        0.66 -0.36    -1.10  0.01
## wind      19.30  0.97     0.86  0.12
## bar        1.22 -0.39    -0.90  0.01
## prec       0.30  1.85     1.98  0.00
#scaling all the variables
dailyscale <- data.frame(scale(dailysub, center=TRUE, scale=TRUE))
#checking and fixing the id variable (which we did not want standardized)
str(dailyscale$id)
##  num [1:1376] -1.77 -1.77 -1.77 -1.77 -1.77 ...
dailyscale$id <- dailysub$id
str(dailyscale$id)
##  num [1:1376] 1010 1011 1012 1013 1014 ...
describe(dailyscale)
##         vars    n mean   sd  median trimmed     mad     min     max   range
## id         1 1376 3276 1280 3271.50 3302.24 1497.43 1010.00 5327.00 4317.00
## slphrs     2 1376    0    1   -0.11    0.00    0.82   -3.98    5.98    9.97
## weath      3 1376    0    1    0.00    0.00    1.15   -1.55    1.54    3.09
## lteq       4 1376    0    1   -0.34   -0.12    0.85   -1.20    4.37    5.57
## pss        5 1376    0    1    0.19    0.03    1.08   -3.83    2.02    5.85
## se         6 1376    0    1   -0.43    0.04    1.49   -2.45    1.58    4.03
## swls       7 1376    0    1    0.07    0.03    0.93   -2.45    2.27    4.72
## evalday    8 1376    0    1    0.68    0.10    0.00   -1.47    0.68    2.15
## posaff     9 1376    0    1    0.08    0.03    1.08   -2.82    2.63    5.45
## negaff    10 1376    0    1   -0.24   -0.11    1.00   -1.40    4.28    5.68
## temp      11 1376    0    1    0.23    0.04    1.13   -2.46    2.01    4.47
## hum       12 1376    0    1    0.20    0.05    1.06   -1.94    1.42    3.36
## wind      13 1376    0    1   -0.08   -0.12    1.00   -1.50    2.84    4.33
## bar       14 1376    0    1   -0.05    0.06    1.29   -2.09    1.56    3.65
## prec      15 1376    0    1   -0.53   -0.26    0.00   -0.53    2.68    3.21
##          skew kurtosis    se
## id      -0.10    -1.04 34.50
## slphrs   0.12     1.93  0.03
## weath   -0.06    -1.06  0.03
## lteq     1.07     0.95  0.03
## pss     -0.37     0.17  0.03
## se      -0.40    -0.12  0.03
## swls    -0.28    -0.22  0.03
## evalday -0.79    -1.37  0.03
## posaff  -0.24    -0.37  0.03
## negaff   0.95     0.67  0.03
## temp    -0.37    -0.24  0.03
## hum     -0.36    -1.10  0.03
## wind     0.97     0.86  0.03
## bar     -0.39    -0.90  0.03
## prec     1.85     1.98  0.03
ggplot(dailyscale,aes(x=lteq,y=posaff)) +
  geom_point()

data1 <- dailyscale[c(1,3,12),c("id","lteq","posaff")]
head(data1,3)
##      id   lteq posaff
## 1  1010 -0.240 -0.189
## 3  1012 -0.240  0.902
## 14 1025 -0.432  0.538
labels.abc <-c("A","B","C")
ggplot(data1,aes(x=lteq,y=posaff)) +
  geom_polygon(fill="blue",alpha=.6) +
  geom_point(size=3) +
  geom_text(aes(x=lteq-.1,label=labels.abc)) +
  ylim(-1,1) + xlim(-1,1)

dist.abc <- dist(data1[1:3,2:3],method="euclidean",diag=TRUE,upper=FALSE)
dist.abc
##        1     3    14
## 1  0.000            
## 3  1.091 0.000      
## 14 0.752 0.411 0.000
dist.abc2 <- dist(data1[1:3,2:3],method="manhattan",diag=TRUE,upper=FALSE)
dist.abc2
##        1     3    14
## 1  0.000            
## 3  1.091 0.000      
## 14 0.919 0.555 0.000
#there are random starts involved so we set a seed
set.seed(1234)
#running a cluster analysis
model <- kmeans(dailyscale[,c("lteq","posaff")], centers=4)
model
## K-means clustering with 4 clusters of sizes 377, 578, 240, 181
## 
## Cluster means:
##     lteq posaff
## 1 -0.656 -1.071
## 2 -0.441  0.700
## 3  0.776 -0.568
## 4  1.744  0.749
## 
## Clustering vector:
##    1    2    3    4    5    6    7    9   10   11   13   14   15   17   18   19 
##    2    1    2    2    3    3    4    2    4    2    2    2    1    2    2    2 
##   20   21   22   23   27   28   29   30   31   32   37   38   39   40   41   42 
##    1    1    1    4    1    1    1    1    2    2    2    2    2    2    1    2 
##   43   44   47   48   49   51   52   53   54   55   56   57   58   59   60   61 
##    2    1    2    2    2    2    2    2    2    1    3    3    1    1    1    3 
##   62   63   64   66   67   68   70   71   72   73   74   75   76   77   78   79 
##    3    2    4    3    1    3    2    2    2    2    2    2    2    1    2    3 
##   81   84   85   86   87   88   89   90   91   92   93   95   96   97   98   99 
##    2    1    3    1    2    2    2    4    4    4    4    2    2    2    2    4 
##  101  102  103  105  106  107  108  110  111  112  113  114  115  116  117  118 
##    4    3    2    3    4    4    3    2    4    4    4    4    4    2    4    4 
##  119  120  121  122  123  124  125  126  127  128  129  130  131  132  133  134 
##    4    3    1    1    1    1    1    1    1    2    2    2    2    2    2    2 
##  135  136  137  138  140  141  143  144  145  146  147  149  150  151  152  153 
##    2    4    4    2    3    3    3    4    3    4    4    4    4    4    1    3 
##  154  155  156  157  158  159  160  161  162  163  164  165  166  167  168  169 
##    2    3    2    3    3    2    2    2    2    2    2    2    2    2    2    2 
##  170  171  172  173  174  175  176  177  178  179  180  181  182  183  184  185 
##    1    2    3    1    1    1    1    1    1    1    1    2    2    2    3    3 
##  186  187  188  189  190  191  192  193  194  196  197  198  199  201  202  203 
##    2    4    4    4    3    3    4    1    1    2    2    2    2    2    4    4 
##  204  205  206  208  209  210  211  212  213  214  215  216  217  218  219  220 
##    2    2    4    4    4    2    2    2    2    2    2    1    2    3    3    1 
##  221  222  223  224  225  226  228  229  230  231  232  233  234  235  236  237 
##    1    3    3    3    3    2    2    2    1    1    2    3    3    2    3    1 
##  238  239  240  241  242  243  244  245  246  247  248  249  250  251  252  253 
##    2    2    1    1    3    3    2    3    3    2    3    2    3    3    3    3 
##  254  255  256  257  258  259  260  261  262  263  264  265  266  267  268  269 
##    3    4    3    3    2    2    2    2    1    2    2    2    2    1    2    1 
##  270  271  272  273  274  275  276  277  278  279  280  281  282  283  285  286 
##    3    3    2    2    2    2    1    1    1    2    1    1    1    3    3    1 
##  287  288  289  290  291  292  293  294  295  296  297  298  299  300  301  302 
##    1    2    2    1    1    1    1    1    1    2    2    2    3    1    2    1 
##  303  304  305  306  307  308  309  312  313  314  315  316  317  318  319  320 
##    3    2    2    2    2    2    1    2    2    2    2    3    3    1    1    2 
##  321  323  324  325  326  327  328  329  330  331  332  333  334  335  343  344 
##    2    2    2    2    2    2    2    4    2    2    2    2    2    2    3    2 
##  345  346  347  348  349  350  352  353  354  355  356  358  359  360  361  364 
##    1    2    1    2    2    2    2    2    2    1    1    1    1    2    4    4 
##  365  366  367  368  369  370  371  372  373  374  376  377  378  379  380  381 
##    4    4    2    2    2    2    3    2    2    3    1    1    1    2    2    1 
##  382  383  384  385  386  387  388  389  390  391  392  393  394  395  396  397 
##    1    2    3    2    3    2    2    3    3    3    3    4    1    1    4    3 
##  398  399  400  401  402  403  404  405  406  407  408  409  410  411  412  413 
##    4    4    4    1    1    4    4    3    4    1    1    1    2    1    1    1 
##  414  415  416  417  418  419  422  423  424  425  426  427  428  429  430  431 
##    1    2    2    2    2    2    1    2    3    3    4    3    3    4    4    2 
##  432  433  434  435  436  437  438  439  441  442  443  444  445  446  447  448 
##    2    2    2    2    3    1    1    3    2    2    3    3    3    3    2    2 
##  449  450  451  452  453  454  455  456  457  458  459  460  461  462  463  464 
##    2    2    2    2    2    2    1    1    1    1    3    3    1    3    2    2 
##  465  466  467  468  469  470  471  472  473  474  475  476  477  478  479  480 
##    1    1    2    2    2    1    2    2    3    3    2    1    1    1    1    1 
##  481  483  485  486  487  488  489  490  491  492  493  494  495  496  497  498 
##    2    1    2    2    2    1    1    1    1    1    1    2    1    2    1    1 
##  499  500  501  502  503  504  505  506  507  508  509  510  511  512  513  514 
##    1    1    2    2    3    3    3    3    3    2    2    2    2    2    2    2 
##  515  516  517  518  519  520  521  522  523  524  525  526  527  528  529  530 
##    1    1    4    3    2    2    4    2    4    4    1    1    1    2    3    3 
##  531  533  534  535  536  537  538  539  540  541  542  543  544  545  546  548 
##    3    3    4    4    4    1    1    1    1    1    1    1    4    4    2    4 
##  549  550  551  552  553  554  555  556  557  558  559  560  561  562  563  564 
##    4    2    2    2    4    3    3    4    1    3    4    2    3    1    1    2 
##  565  566  567  568  569  570  571  572  573  574  575  576  577  578  579  580 
##    3    1    1    2    2    2    2    2    2    2    2    1    3    4    4    4 
##  581  582  583  584  585  586  587  588  589  590  591  592  593  594  595  596 
##    3    1    1    1    2    2    1    1    2    1    1    2    1    1    1    2 
##  597  598  599  601  602  603  604  605  606  607  609  610  611  612  613  614 
##    1    1    1    2    1    1    2    1    1    1    2    2    2    2    1    1 
##  615  616  617  618  619  620  621  622  623  624  625  626  628  629  630  631 
##    2    2    2    3    2    2    3    1    1    2    2    2    2    2    2    2 
##  632  633  634  635  636  637  638  639  640  641  642  643  644  645  646  647 
##    1    1    1    3    1    2    1    1    2    3    2    3    1    1    1    1 
##  648  649  650  651  652  653  654  655  656  657  658  659  660  661  662  663 
##    1    2    3    1    1    1    3    4    3    1    1    1    1    1    1    3 
##  664  665  666  667  668  669  670  671  672  673  674  675  676  677  678  679 
##    3    4    4    4    4    4    4    3    4    4    4    2    2    1    4    2 
##  680  681  682  684  685  686  687  688  689  690  691  692  693  694  696  697 
##    2    2    2    1    3    2    2    4    4    2    2    2    4    4    2    1 
##  698  699  700  701  702  703  704  705  706  707  708  709  710  711  712  713 
##    1    2    1    1    1    3    3    3    3    3    3    1    3    1    1    1 
##  714  715  716  717  719  720  721  722  723  724  725  726  727  728  731  735 
##    2    1    1    1    1    1    3    1    1    1    1    3    4    4    4    2 
##  736  737  738  739  740  741  742  743  744  745  746  747  748  749  750  751 
##    4    2    4    4    3    3    3    4    3    3    2    4    3    3    2    2 
##  752  753  754  755  757  758  759  760  761  762  763  764  765  766  767  768 
##    3    3    2    2    1    2    2    1    1    2    2    1    2    2    2    2 
##  769  770  771  772  773  774  775  776  777  778  779  780  781  782  783  784 
##    2    1    2    2    3    1    3    3    3    1    1    1    3    1    1    1 
##  785  786  787  788  789  790  791  792  793  794  795  796  797  798  799  800 
##    1    1    1    1    2    2    1    1    4    4    4    1    3    2    4    4 
##  801  802  803  804  805  806  807  808  809  810  811  812  813  814  815  816 
##    4    4    4    1    3    1    2    2    2    2    2    2    2    1    1    1 
##  817  819  820  821  822  823  824  825  826  827  828  829  830  831  832  833 
##    2    1    1    1    1    2    2    2    1    2    1    4    1    1    2    2 
##  834  835  836  837  838  839  840  841  842  843  844  845  846  847  848  849 
##    1    4    1    2    2    2    1    2    2    2    3    3    3    1    3    2 
##  850  851  852  853  854  855  856  857  858  859  860  861  862  863  864  866 
##    2    1    2    1    3    2    2    4    4    2    4    2    4    4    3    4 
##  867  868  869  871  872  873  874  875  876  877  878  879  880  881  882  883 
##    3    4    4    3    4    3    4    1    1    4    1    1    2    1    2    1 
##  884  885  886  887  888  889  890  891  892  893  894  895  896  897  898  899 
##    1    2    2    1    1    1    2    1    2    2    3    3    2    2    1    2 
##  900  901  902  903  904  905  906  907  908  909  910  911  912  913  914  915 
##    2    2    2    2    2    1    3    1    2    2    3    3    3    1    3    3 
##  916  917  918  919  920  921  922  923  924  925  926  927  928  929  930  931 
##    3    3    2    3    2    3    2    1    2    1    2    2    1    2    2    2 
##  932  933  934  935  936  937  938  940  942  943  944  945  946  947  948  949 
##    1    2    4    4    4    4    4    2    2    2    2    2    1    3    2    2 
##  950  951  952  953  956  957  958  959  960  961  962  963  964  965  966  967 
##    3    3    2    1    1    1    2    2    2    3    3    3    3    2    3    3 
##  968  969  970  971  972  973  974  976  977  978  979  980  982  983  984  985 
##    2    1    1    3    4    3    1    2    2    3    3    3    2    2    2    2 
##  986  987  988  989  990  991  992  993  994  995  996  997  998  999 1000 1001 
##    1    3    3    1    3    3    2    2    4    3    3    3    1    2    3    1 
## 1002 1003 1004 1005 1006 1007 1008 1009 1011 1012 1013 1014 1015 1016 1017 1018 
##    3    4    3    4    1    2    2    2    1    1    2    3    3    3    4    4 
## 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 
##    2    2    2    1    3    3    3    4    4    1    2    1    3    1    1    1 
## 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 
##    1    1    1    2    2    2    2    2    2    2    2    4    2    2    2    2 
## 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1064 1065 1066 1067 
##    4    2    4    2    2    2    2    1    1    1    1    3    3    1    3    2 
## 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 
##    2    3    2    4    2    3    3    3    4    2    2    2    2    1    2    1 
## 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 
##    3    2    2    2    2    2    2    2    2    2    2    2    2    2    2    2 
## 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 
##    2    2    1    2    1    1    2    1    2    2    4    2    4    2    2    2 
## 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 
##    2    2    2    3    3    3    1    3    2    2    2    2    2    2    4    4 
## 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 
##    4    2    2    4    2    4    4    3    4    4    2    2    2    3    2    2 
## 1148 1149 1150 1151 1152 1153 1154 1156 1157 1158 1160 1161 1162 1163 1164 1165 
##    2    2    2    2    1    2    2    1    2    1    2    2    2    1    1    1 
## 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 
##    2    4    4    1    3    1    4    2    4    3    3    2    3    3    4    4 
## 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 
##    1    2    2    1    2    2    3    1    3    3    4    2    2    4    2    4 
## 1198 1199 1200 1201 1202 1203 1204 1205 1207 1208 1209 1210 1211 1212 1213 1215 
##    2    2    2    2    2    2    1    1    2    1    2    2    2    2    2    2 
## 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 
##    2    1    2    2    2    2    1    2    1    2    2    1    2    1    4    4 
## 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 
##    4    3    4    4    3    3    2    2    1    2    2    2    1    1    2    2 
## 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 
##    2    3    1    2    4    2    4    4    2    4    4    4    3    4    2    2 
## 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 
##    2    2    3    2    1    3    2    3    4    4    1    2    2    4    2    2 
## 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 
##    2    2    1    1    1    1    2    1    1    1    2    2    2    2    2    2 
## 1296 1297 1298 1299 1300 1301 1302 1304 1305 1306 1307 1308 1309 1310 1311 1312 
##    3    1    3    2    2    2    2    1    1    1    1    2    2    2    2    2 
## 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 
##    2    2    2    2    1    2    2    2    2    1    2    2    2    1    2    1 
## 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 
##    1    1    1    4    1    3    2    3    3    3    3    2    2    2    2    2 
## 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 
##    1    2    2    2    2    2    2    2    2    2    2    2    2    2    2    2 
## 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 
##    2    2    2    2    2    2    2    2    1    2    2    4    4    3    1    4 
## 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 
##    3    3    3    4    1    2    2    4    4    4    4    1    1    1    1    1 
## 1393 1394 1395 1396 1397 1398 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 
##    1    1    1    3    3    3    2    3    3    4    1    1    2    2    1    2 
## 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 
##    3    2    1    2    2    1    1    1    1    2    1    2    1    1    1    1 
## 1426 1427 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 
##    1    2    4    4    4    3    1    3    4    3    1    1    1    1    1    1 
## 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 
##    2    1    1    1    1    1    1    1    3    1    2    2    1    3    2    2 
## 
## Within cluster sum of squares by cluster:
## [1] 201 329 176 180
##  (between_SS / total_SS =  67.8 %)
## 
## Available components:
## 
## [1] "cluster"      "centers"      "totss"        "withinss"     "tot.withinss"
## [6] "betweenss"    "size"         "iter"         "ifault"
#getting centers
model$centers
##     lteq posaff
## 1 -0.656 -1.071
## 2 -0.441  0.700
## 3  0.776 -0.568
## 4  1.744  0.749
#plotting clustered data points with k means
ggplot(dailyscale,aes(x=lteq,y=posaff)) +
  geom_point(color=model$cluster, alpha=.6) +#plotting alll the points
  #plotting the centroids
  geom_point(aes(x=model$centers[1,1],y=model$centers[1,2]),color=1,size=5,shape=18) +
  geom_point(aes(x=model$centers[2,1],y=model$centers[2,2]),color=2,size=5,shape=18) +
  geom_point(aes(x=model$centers[3,1],y=model$centers[3,2]),color=3,size=5,shape=18) +
  geom_point(aes(x=model$centers[4,1],y=model$centers[4,2]),color=4,size=5,shape=18) 

library(animation)
kmeans.ani(dailyscale[,c("lteq","posaff")], centers = 4, pch=c(15,16,17,18), col=c(1,2,3,4))

model$totss
## [1] 2750
model$withinss
## [1] 201 329 176 180
model$tot.withinss
## [1] 886
model$betweenss
## [1] 1864
#making a empty dataframe
criteria <- data.frame()
#setting range of k                   
nk <- 1:20
#loop for range of clusters
for (k in nk) {
model <- kmeans(dailyscale[,c("lteq","posaff")], k)
criteria <- rbind(criteria,c(k,model$tot.withinss,model$betweenss,model$totss))
}
#renaming columns
names(criteria) <- c("k","tot.withinss","betweenss","totalss")

#scree plot
ggplot(criteria, aes(x=k)) +
  geom_point(aes(y=tot.withinss),color="red") +
  geom_line(aes(y=tot.withinss),color="red") +
  geom_point(aes(y=betweenss),color="blue") +
  geom_line(aes(y=betweenss),color="blue") +
  xlab("k = number of clusters") + ylab("Sum of Squares (within = red, between = blue)")

#looking at criteria
round(criteria,2)
##     k tot.withinss betweenss totalss
## 1   1         2750         0    2750
## 2   2         1789       961    2750
## 3   3         1083      1667    2750
## 4   4          887      1863    2750
## 5   5          714      2036    2750
## 6   6          583      2167    2750
## 7   7          497      2253    2750
## 8   8          466      2284    2750
## 9   9          408      2342    2750
## 10 10          378      2372    2750
## 11 11          340      2410    2750
## 12 12          297      2453    2750
## 13 13          291      2459    2750
## 14 14          283      2467    2750
## 15 15          251      2499    2750
## 16 16          234      2516    2750
## 17 17          217      2533    2750
## 18 18          204      2546    2750
## 19 19          207      2543    2750
## 20 20          186      2564    2750
#from library(fpc)
model.manyCH <- kmeansruns(dailyscale[,c("lteq","posaff")], krange=c(2:20), criterion="ch",critout = TRUE, plot=FALSE) #better to leave the plot FALSE
## 2  clusters  745 
## 3  clusters  1057 
## 4  clusters  975 
## 5  clusters  978 
## 6  clusters  1019 
## 7  clusters  1034 
## 8  clusters  1017 
## 9  clusters  1016 
## 10  clusters  1011 
## 11  clusters  1014 
## 12  clusters  1025 
## 13  clusters  1017 
## 14  clusters  1008 
## 15  clusters  1009 
## 16  clusters  1009 
## 17  clusters  1016 
## 18  clusters  1020 
## 19  clusters  1017 
## 20  clusters  1019
model.manyCH
## K-means clustering with 3 clusters of sizes 484, 631, 261
## 
## Cluster means:
##     lteq posaff
## 1 -0.434 -1.004
## 2 -0.346  0.690
## 3  1.641  0.195
## 
## Clustering vector:
##    1    2    3    4    5    6    7    9   10   11   13   14   15   17   18   19 
##    1    1    2    2    2    3    3    2    2    2    2    2    1    2    2    2 
##   20   21   22   23   27   28   29   30   31   32   37   38   39   40   41   42 
##    1    1    1    2    1    1    1    1    2    2    2    2    2    2    1    2 
##   43   44   47   48   49   51   52   53   54   55   56   57   58   59   60   61 
##    2    1    2    2    2    2    2    2    2    1    3    1    1    1    1    1 
##   62   63   64   66   67   68   70   71   72   73   74   75   76   77   78   79 
##    3    2    2    1    1    2    2    2    2    2    2    2    2    1    2    2 
##   81   84   85   86   87   88   89   90   91   92   93   95   96   97   98   99 
##    2    1    1    1    2    2    2    3    3    3    3    2    2    2    2    3 
##  101  102  103  105  106  107  108  110  111  112  113  114  115  116  117  118 
##    3    3    2    1    3    3    3    2    3    3    3    3    3    2    3    3 
##  119  120  121  122  123  124  125  126  127  128  129  130  131  132  133  134 
##    3    1    1    1    1    1    1    1    1    2    2    2    2    2    2    2 
##  135  136  137  138  140  141  143  144  145  146  147  149  150  151  152  153 
##    2    3    3    2    3    2    3    3    2    3    3    3    3    3    1    3 
##  154  155  156  157  158  159  160  161  162  163  164  165  166  167  168  169 
##    2    2    2    3    2    2    2    2    2    2    2    2    2    1    2    2 
##  170  171  172  173  174  175  176  177  178  179  180  181  182  183  184  185 
##    1    2    2    1    1    1    1    1    1    1    1    2    2    2    1    2 
##  186  187  188  189  190  191  192  193  194  196  197  198  199  201  202  203 
##    2    3    3    3    1    3    3    1    1    2    2    2    2    2    3    3 
##  204  205  206  208  209  210  211  212  213  214  215  216  217  218  219  220 
##    2    2    3    3    3    2    2    2    2    2    2    1    2    1    1    1 
##  221  222  223  224  225  226  228  229  230  231  232  233  234  235  236  237 
##    1    3    1    1    1    2    2    2    1    1    2    2    2    2    1    1 
##  238  239  240  241  242  243  244  245  246  247  248  249  250  251  252  253 
##    2    1    1    1    2    2    2    3    3    2    3    2    3    1    3    3 
##  254  255  256  257  258  259  260  261  262  263  264  265  266  267  268  269 
##    1    3    3    3    2    2    2    2    1    2    2    2    2    1    2    1 
##  270  271  272  273  274  275  276  277  278  279  280  281  282  283  285  286 
##    3    2    2    2    2    2    1    1    1    2    1    1    1    1    1    1 
##  287  288  289  290  291  292  293  294  295  296  297  298  299  300  301  302 
##    1    1    2    1    1    1    1    1    1    2    2    2    1    1    2    1 
##  303  304  305  306  307  308  309  312  313  314  315  316  317  318  319  320 
##    2    2    2    2    2    2    1    2    2    2    2    2    3    1    1    2 
##  321  323  324  325  326  327  328  329  330  331  332  333  334  335  343  344 
##    2    2    2    2    2    2    2    2    2    2    2    2    2    2    1    2 
##  345  346  347  348  349  350  352  353  354  355  356  358  359  360  361  364 
##    1    2    1    2    2    2    2    2    2    1    1    1    1    2    2    3 
##  365  366  367  368  369  370  371  372  373  374  376  377  378  379  380  381 
##    3    3    2    2    2    2    2    2    2    2    1    1    1    2    2    1 
##  382  383  384  385  386  387  388  389  390  391  392  393  394  395  396  397 
##    1    2    1    2    3    2    2    1    1    2    3    3    1    1    3    3 
##  398  399  400  401  402  403  404  405  406  407  408  409  410  411  412  413 
##    3    3    3    1    1    3    3    1    3    1    1    1    2    1    1    1 
##  414  415  416  417  418  419  422  423  424  425  426  427  428  429  430  431 
##    1    2    2    2    2    2    1    2    3    2    3    3    2    3    3    2 
##  432  433  434  435  436  437  438  439  441  442  443  444  445  446  447  448 
##    2    2    2    2    2    1    1    3    2    2    1    1    3    3    2    2 
##  449  450  451  452  453  454  455  456  457  458  459  460  461  462  463  464 
##    2    2    2    2    2    2    1    1    1    1    1    1    1    1    2    2 
##  465  466  467  468  469  470  471  472  473  474  475  476  477  478  479  480 
##    1    1    2    2    2    1    2    2    3    2    2    1    1    1    1    1 
##  481  483  485  486  487  488  489  490  491  492  493  494  495  496  497  498 
##    2    1    2    2    2    1    1    1    1    1    1    2    1    2    1    1 
##  499  500  501  502  503  504  505  506  507  508  509  510  511  512  513  514 
##    1    1    2    2    1    1    1    1    1    2    2    2    2    2    2    2 
##  515  516  517  518  519  520  521  522  523  524  525  526  527  528  529  530 
##    1    1    2    3    2    2    3    2    3    3    1    1    1    2    3    1 
##  531  533  534  535  536  537  538  539  540  541  542  543  544  545  546  548 
##    3    1    3    3    3    1    1    1    1    1    1    1    2    3    2    3 
##  549  550  551  552  553  554  555  556  557  558  559  560  561  562  563  564 
##    3    2    2    2    3    3    3    3    1    3    3    2    2    1    1    2 
##  565  566  567  568  569  570  571  572  573  574  575  576  577  578  579  580 
##    3    1    1    2    2    2    2    2    2    2    2    1    3    3    3    3 
##  581  582  583  584  585  586  587  588  589  590  591  592  593  594  595  596 
##    1    1    1    1    2    2    1    1    2    1    1    2    1    1    1    2 
##  597  598  599  601  602  603  604  605  606  607  609  610  611  612  613  614 
##    1    1    1    2    1    1    2    1    1    1    2    2    2    2    1    1 
##  615  616  617  618  619  620  621  622  623  624  625  626  628  629  630  631 
##    2    2    2    2    2    2    1    1    1    2    2    2    2    2    2    2 
##  632  633  634  635  636  637  638  639  640  641  642  643  644  645  646  647 
##    1    1    1    1    1    2    1    1    2    2    2    1    1    1    1    1 
##  648  649  650  651  652  653  654  655  656  657  658  659  660  661  662  663 
##    1    2    1    1    1    1    2    3    3    1    1    1    1    1    1    1 
##  664  665  666  667  668  669  670  671  672  673  674  675  676  677  678  679 
##    3    3    3    3    3    3    3    3    3    3    3    2    2    1    3    2 
##  680  681  682  684  685  686  687  688  689  690  691  692  693  694  696  697 
##    2    2    2    1    1    2    2    3    3    2    2    2    3    3    2    1 
##  698  699  700  701  702  703  704  705  706  707  708  709  710  711  712  713 
##    1    2    1    1    1    1    3    3    3    3    1    1    3    1    1    1 
##  714  715  716  717  719  720  721  722  723  724  725  726  727  728  731  735 
##    2    1    1    1    1    1    2    1    1    1    1    1    3    3    3    2 
##  736  737  738  739  740  741  742  743  744  745  746  747  748  749  750  751 
##    3    2    2    3    1    1    1    3    2    2    2    3    1    3    2    2 
##  752  753  754  755  757  758  759  760  761  762  763  764  765  766  767  768 
##    1    1    2    2    1    2    1    1    1    2    2    1    2    2    2    2 
##  769  770  771  772  773  774  775  776  777  778  779  780  781  782  783  784 
##    2    1    2    2    1    1    3    1    3    1    1    1    1    1    1    1 
##  785  786  787  788  789  790  791  792  793  794  795  796  797  798  799  800 
##    1    1    1    1    2    2    1    1    3    3    3    1    3    2    3    3 
##  801  802  803  804  805  806  807  808  809  810  811  812  813  814  815  816 
##    3    3    3    1    3    1    2    2    2    2    2    2    2    1    1    1 
##  817  819  820  821  822  823  824  825  826  827  828  829  830  831  832  833 
##    2    1    1    1    1    2    2    2    1    2    1    3    1    1    2    2 
##  834  835  836  837  838  839  840  841  842  843  844  845  846  847  848  849 
##    1    3    1    2    2    2    1    2    2    2    2    1    1    1    3    2 
##  850  851  852  853  854  855  856  857  858  859  860  861  862  863  864  866 
##    2    1    2    1    3    2    2    2    3    2    3    2    3    3    3    3 
##  867  868  869  871  872  873  874  875  876  877  878  879  880  881  882  883 
##    2    3    3    2    3    3    3    1    1    3    1    1    2    1    2    1 
##  884  885  886  887  888  889  890  891  892  893  894  895  896  897  898  899 
##    1    2    2    1    1    1    2    1    2    2    2    1    2    2    1    2 
##  900  901  902  903  904  905  906  907  908  909  910  911  912  913  914  915 
##    2    2    2    2    2    1    1    1    2    2    1    2    1    1    3    3 
##  916  917  918  919  920  921  922  923  924  925  926  927  928  929  930  931 
##    1    3    2    2    2    2    1    1    2    1    2    2    1    2    2    2 
##  932  933  934  935  936  937  938  940  942  943  944  945  946  947  948  949 
##    1    2    3    3    3    3    3    2    2    2    2    2    1    1    1    2 
##  950  951  952  953  956  957  958  959  960  961  962  963  964  965  966  967 
##    3    2    2    1    1    1    2    2    2    1    1    1    1    2    3    3 
##  968  969  970  971  972  973  974  976  977  978  979  980  982  983  984  985 
##    2    1    1    3    3    3    1    2    2    3    1    1    2    2    2    1 
##  986  987  988  989  990  991  992  993  994  995  996  997  998  999 1000 1001 
##    1    3    1    1    2    3    2    2    3    1    3    1    1    2    3    1 
## 1002 1003 1004 1005 1006 1007 1008 1009 1011 1012 1013 1014 1015 1016 1017 1018 
##    3    3    1    3    1    2    2    2    1    1    2    1    1    3    3    3 
## 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 
##    2    2    2    1    3    1    2    3    3    1    2    1    1    1    1    1 
## 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 
##    1    1    1    2    2    2    2    2    2    2    2    2    2    2    2    2 
## 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1064 1065 1066 1067 
##    3    2    3    2    2    2    2    1    1    1    1    2    3    1    1    2 
## 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 
##    2    2    2    3    2    3    1    3    3    2    2    2    2    1    2    1 
## 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 
##    2    2    2    2    2    2    2    2    2    2    2    2    2    2    2    2 
## 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 
##    2    2    1    2    1    1    2    1    2    2    3    2    2    2    2    2 
## 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 
##    2    2    2    2    3    3    1    3    2    1    2    2    2    2    3    3 
## 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 
##    3    2    2    3    2    3    3    3    3    3    2    2    2    2    2    2 
## 1148 1149 1150 1151 1152 1153 1154 1156 1157 1158 1160 1161 1162 1163 1164 1165 
##    2    2    2    2    1    2    2    1    2    1    2    2    2    1    1    1 
## 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 
##    2    3    3    1    1    1    3    2    3    3    1    2    1    2    3    2 
## 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 
##    1    2    2    1    2    2    1    1    1    3    3    1    2    3    2    3 
## 1198 1199 1200 1201 1202 1203 1204 1205 1207 1208 1209 1210 1211 1212 1213 1215 
##    2    2    2    2    2    2    1    1    2    1    2    2    2    2    2    2 
## 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 
##    2    1    2    2    2    2    1    2    1    2    2    1    2    1    3    3 
## 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 
##    3    3    3    3    1    1    2    2    1    2    2    2    1    1    1    2 
## 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 
##    2    2    1    2    3    2    3    2    2    3    3    3    3    3    2    2 
## 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 
##    2    2    1    2    1    2    2    2    3    3    1    2    2    3    2    2 
## 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 
##    2    2    1    1    1    1    2    1    1    1    2    2    2    2    2    2 
## 1296 1297 1298 1299 1300 1301 1302 1304 1305 1306 1307 1308 1309 1310 1311 1312 
##    1    1    1    2    2    2    2    1    1    1    1    2    2    2    2    2 
## 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 
##    2    1    2    2    1    2    2    2    2    1    2    2    2    1    2    1 
## 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 
##    1    1    1    3    1    3    2    1    3    3    3    2    2    2    2    2 
## 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 
##    1    2    2    2    2    2    2    2    2    2    2    2    2    2    2    2 
## 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 
##    2    2    2    2    2    2    2    2    1    2    2    3    3    1    1    3 
## 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 
##    3    3    3    3    1    2    2    3    2    3    2    1    1    1    1    1 
## 1393 1394 1395 1396 1397 1398 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 
##    1    1    1    3    1    3    2    3    1    3    1    1    2    2    1    2 
## 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 
##    1    2    1    2    2    1    1    1    1    2    1    2    1    1    1    1 
## 1426 1427 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 
##    1    2    3    3    3    3    1    3    3    2    1    1    1    1    1    1 
## 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 
##    2    1    1    1    1    1    1    1    3    1    2    2    1    1    2    2 
## 
## Within cluster sum of squares by cluster:
## [1] 335 413 334
##  (between_SS / total_SS =  60.6 %)
## 
## Available components:
## 
##  [1] "cluster"      "centers"      "totss"        "withinss"     "tot.withinss"
##  [6] "betweenss"    "size"         "iter"         "ifault"       "crit"        
## [11] "bestk"
#another criteria 
model.manyASW <- kmeansruns(dailyscale[,c("lteq","posaff")], krange=c(2:20), criterion="asw",critout = TRUE, plot=FALSE) #better to leave the plot FALSE
## 2  clusters  0.332 
## 3  clusters  0.388 
## 4  clusters  0.354 
## 5  clusters  0.343 
## 6  clusters  0.35 
## 7  clusters  0.357 
## 8  clusters  0.342 
## 9  clusters  0.348 
## 10  clusters  0.353 
## 11  clusters  0.36 
## 12  clusters  0.363 
## 13  clusters  0.358 
## 14  clusters  0.361 
## 15  clusters  0.363 
## 16  clusters  0.362 
## 17  clusters  0.362 
## 18  clusters  0.362 
## 19  clusters  0.365 
## 20  clusters  0.358
model.manyASW
## K-means clustering with 3 clusters of sizes 631, 484, 261
## 
## Cluster means:
##     lteq posaff
## 1 -0.346  0.690
## 2 -0.434 -1.004
## 3  1.641  0.195
## 
## Clustering vector:
##    1    2    3    4    5    6    7    9   10   11   13   14   15   17   18   19 
##    2    2    1    1    1    3    3    1    1    1    1    1    2    1    1    1 
##   20   21   22   23   27   28   29   30   31   32   37   38   39   40   41   42 
##    2    2    2    1    2    2    2    2    1    1    1    1    1    1    2    1 
##   43   44   47   48   49   51   52   53   54   55   56   57   58   59   60   61 
##    1    2    1    1    1    1    1    1    1    2    3    2    2    2    2    2 
##   62   63   64   66   67   68   70   71   72   73   74   75   76   77   78   79 
##    3    1    1    2    2    1    1    1    1    1    1    1    1    2    1    1 
##   81   84   85   86   87   88   89   90   91   92   93   95   96   97   98   99 
##    1    2    2    2    1    1    1    3    3    3    3    1    1    1    1    3 
##  101  102  103  105  106  107  108  110  111  112  113  114  115  116  117  118 
##    3    3    1    2    3    3    3    1    3    3    3    3    3    1    3    3 
##  119  120  121  122  123  124  125  126  127  128  129  130  131  132  133  134 
##    3    2    2    2    2    2    2    2    2    1    1    1    1    1    1    1 
##  135  136  137  138  140  141  143  144  145  146  147  149  150  151  152  153 
##    1    3    3    1    3    1    3    3    1    3    3    3    3    3    2    3 
##  154  155  156  157  158  159  160  161  162  163  164  165  166  167  168  169 
##    1    1    1    3    1    1    1    1    1    1    1    1    1    2    1    1 
##  170  171  172  173  174  175  176  177  178  179  180  181  182  183  184  185 
##    2    1    1    2    2    2    2    2    2    2    2    1    1    1    2    1 
##  186  187  188  189  190  191  192  193  194  196  197  198  199  201  202  203 
##    1    3    3    3    2    3    3    2    2    1    1    1    1    1    3    3 
##  204  205  206  208  209  210  211  212  213  214  215  216  217  218  219  220 
##    1    1    3    3    3    1    1    1    1    1    1    2    1    2    2    2 
##  221  222  223  224  225  226  228  229  230  231  232  233  234  235  236  237 
##    2    3    2    2    2    1    1    1    2    2    1    1    1    1    2    2 
##  238  239  240  241  242  243  244  245  246  247  248  249  250  251  252  253 
##    1    2    2    2    1    1    1    3    3    1    3    1    3    2    3    3 
##  254  255  256  257  258  259  260  261  262  263  264  265  266  267  268  269 
##    2    3    3    3    1    1    1    1    2    1    1    1    1    2    1    2 
##  270  271  272  273  274  275  276  277  278  279  280  281  282  283  285  286 
##    3    1    1    1    1    1    2    2    2    1    2    2    2    2    2    2 
##  287  288  289  290  291  292  293  294  295  296  297  298  299  300  301  302 
##    2    2    1    2    2    2    2    2    2    1    1    1    2    2    1    2 
##  303  304  305  306  307  308  309  312  313  314  315  316  317  318  319  320 
##    1    1    1    1    1    1    2    1    1    1    1    1    3    2    2    1 
##  321  323  324  325  326  327  328  329  330  331  332  333  334  335  343  344 
##    1    1    1    1    1    1    1    1    1    1    1    1    1    1    2    1 
##  345  346  347  348  349  350  352  353  354  355  356  358  359  360  361  364 
##    2    1    2    1    1    1    1    1    1    2    2    2    2    1    1    3 
##  365  366  367  368  369  370  371  372  373  374  376  377  378  379  380  381 
##    3    3    1    1    1    1    1    1    1    1    2    2    2    1    1    2 
##  382  383  384  385  386  387  388  389  390  391  392  393  394  395  396  397 
##    2    1    2    1    3    1    1    2    2    1    3    3    2    2    3    3 
##  398  399  400  401  402  403  404  405  406  407  408  409  410  411  412  413 
##    3    3    3    2    2    3    3    2    3    2    2    2    1    2    2    2 
##  414  415  416  417  418  419  422  423  424  425  426  427  428  429  430  431 
##    2    1    1    1    1    1    2    1    3    1    3    3    1    3    3    1 
##  432  433  434  435  436  437  438  439  441  442  443  444  445  446  447  448 
##    1    1    1    1    1    2    2    3    1    1    2    2    3    3    1    1 
##  449  450  451  452  453  454  455  456  457  458  459  460  461  462  463  464 
##    1    1    1    1    1    1    2    2    2    2    2    2    2    2    1    1 
##  465  466  467  468  469  470  471  472  473  474  475  476  477  478  479  480 
##    2    2    1    1    1    2    1    1    3    1    1    2    2    2    2    2 
##  481  483  485  486  487  488  489  490  491  492  493  494  495  496  497  498 
##    1    2    1    1    1    2    2    2    2    2    2    1    2    1    2    2 
##  499  500  501  502  503  504  505  506  507  508  509  510  511  512  513  514 
##    2    2    1    1    2    2    2    2    2    1    1    1    1    1    1    1 
##  515  516  517  518  519  520  521  522  523  524  525  526  527  528  529  530 
##    2    2    1    3    1    1    3    1    3    3    2    2    2    1    3    2 
##  531  533  534  535  536  537  538  539  540  541  542  543  544  545  546  548 
##    3    2    3    3    3    2    2    2    2    2    2    2    1    3    1    3 
##  549  550  551  552  553  554  555  556  557  558  559  560  561  562  563  564 
##    3    1    1    1    3    3    3    3    2    3    3    1    1    2    2    1 
##  565  566  567  568  569  570  571  572  573  574  575  576  577  578  579  580 
##    3    2    2    1    1    1    1    1    1    1    1    2    3    3    3    3 
##  581  582  583  584  585  586  587  588  589  590  591  592  593  594  595  596 
##    2    2    2    2    1    1    2    2    1    2    2    1    2    2    2    1 
##  597  598  599  601  602  603  604  605  606  607  609  610  611  612  613  614 
##    2    2    2    1    2    2    1    2    2    2    1    1    1    1    2    2 
##  615  616  617  618  619  620  621  622  623  624  625  626  628  629  630  631 
##    1    1    1    1    1    1    2    2    2    1    1    1    1    1    1    1 
##  632  633  634  635  636  637  638  639  640  641  642  643  644  645  646  647 
##    2    2    2    2    2    1    2    2    1    1    1    2    2    2    2    2 
##  648  649  650  651  652  653  654  655  656  657  658  659  660  661  662  663 
##    2    1    2    2    2    2    1    3    3    2    2    2    2    2    2    2 
##  664  665  666  667  668  669  670  671  672  673  674  675  676  677  678  679 
##    3    3    3    3    3    3    3    3    3    3    3    1    1    2    3    1 
##  680  681  682  684  685  686  687  688  689  690  691  692  693  694  696  697 
##    1    1    1    2    2    1    1    3    3    1    1    1    3    3    1    2 
##  698  699  700  701  702  703  704  705  706  707  708  709  710  711  712  713 
##    2    1    2    2    2    2    3    3    3    3    2    2    3    2    2    2 
##  714  715  716  717  719  720  721  722  723  724  725  726  727  728  731  735 
##    1    2    2    2    2    2    1    2    2    2    2    2    3    3    3    1 
##  736  737  738  739  740  741  742  743  744  745  746  747  748  749  750  751 
##    3    1    1    3    2    2    2    3    1    1    1    3    2    3    1    1 
##  752  753  754  755  757  758  759  760  761  762  763  764  765  766  767  768 
##    2    2    1    1    2    1    2    2    2    1    1    2    1    1    1    1 
##  769  770  771  772  773  774  775  776  777  778  779  780  781  782  783  784 
##    1    2    1    1    2    2    3    2    3    2    2    2    2    2    2    2 
##  785  786  787  788  789  790  791  792  793  794  795  796  797  798  799  800 
##    2    2    2    2    1    1    2    2    3    3    3    2    3    1    3    3 
##  801  802  803  804  805  806  807  808  809  810  811  812  813  814  815  816 
##    3    3    3    2    3    2    1    1    1    1    1    1    1    2    2    2 
##  817  819  820  821  822  823  824  825  826  827  828  829  830  831  832  833 
##    1    2    2    2    2    1    1    1    2    1    2    3    2    2    1    1 
##  834  835  836  837  838  839  840  841  842  843  844  845  846  847  848  849 
##    2    3    2    1    1    1    2    1    1    1    1    2    2    2    3    1 
##  850  851  852  853  854  855  856  857  858  859  860  861  862  863  864  866 
##    1    2    1    2    3    1    1    1    3    1    3    1    3    3    3    3 
##  867  868  869  871  872  873  874  875  876  877  878  879  880  881  882  883 
##    1    3    3    1    3    3    3    2    2    3    2    2    1    2    1    2 
##  884  885  886  887  888  889  890  891  892  893  894  895  896  897  898  899 
##    2    1    1    2    2    2    1    2    1    1    1    2    1    1    2    1 
##  900  901  902  903  904  905  906  907  908  909  910  911  912  913  914  915 
##    1    1    1    1    1    2    2    2    1    1    2    1    2    2    3    3 
##  916  917  918  919  920  921  922  923  924  925  926  927  928  929  930  931 
##    2    3    1    1    1    1    2    2    1    2    1    1    2    1    1    1 
##  932  933  934  935  936  937  938  940  942  943  944  945  946  947  948  949 
##    2    1    3    3    3    3    3    1    1    1    1    1    2    2    2    1 
##  950  951  952  953  956  957  958  959  960  961  962  963  964  965  966  967 
##    3    1    1    2    2    2    1    1    1    2    2    2    2    1    3    3 
##  968  969  970  971  972  973  974  976  977  978  979  980  982  983  984  985 
##    1    2    2    3    3    3    2    1    1    3    2    2    1    1    1    2 
##  986  987  988  989  990  991  992  993  994  995  996  997  998  999 1000 1001 
##    2    3    2    2    1    3    1    1    3    2    3    2    2    1    3    2 
## 1002 1003 1004 1005 1006 1007 1008 1009 1011 1012 1013 1014 1015 1016 1017 1018 
##    3    3    2    3    2    1    1    1    2    2    1    2    2    3    3    3 
## 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 
##    1    1    1    2    3    2    1    3    3    2    1    2    2    2    2    2 
## 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 
##    2    2    2    1    1    1    1    1    1    1    1    1    1    1    1    1 
## 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1064 1065 1066 1067 
##    3    1    3    1    1    1    1    2    2    2    2    1    3    2    2    1 
## 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 
##    1    1    1    3    1    3    2    3    3    1    1    1    1    2    1    2 
## 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 
##    1    1    1    1    1    1    1    1    1    1    1    1    1    1    1    1 
## 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 
##    1    1    2    1    2    2    1    2    1    1    3    1    1    1    1    1 
## 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 
##    1    1    1    1    3    3    2    3    1    2    1    1    1    1    3    3 
## 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 
##    3    1    1    3    1    3    3    3    3    3    1    1    1    1    1    1 
## 1148 1149 1150 1151 1152 1153 1154 1156 1157 1158 1160 1161 1162 1163 1164 1165 
##    1    1    1    1    2    1    1    2    1    2    1    1    1    2    2    2 
## 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 
##    1    3    3    2    2    2    3    1    3    3    2    1    2    1    3    1 
## 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 
##    2    1    1    2    1    1    2    2    2    3    3    2    1    3    1    3 
## 1198 1199 1200 1201 1202 1203 1204 1205 1207 1208 1209 1210 1211 1212 1213 1215 
##    1    1    1    1    1    1    2    2    1    2    1    1    1    1    1    1 
## 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 
##    1    2    1    1    1    1    2    1    2    1    1    2    1    2    3    3 
## 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 
##    3    3    3    3    2    2    1    1    2    1    1    1    2    2    2    1 
## 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 
##    1    1    2    1    3    1    3    1    1    3    3    3    3    3    1    1 
## 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 
##    1    1    2    1    2    1    1    1    3    3    2    1    1    3    1    1 
## 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 
##    1    1    2    2    2    2    1    2    2    2    1    1    1    1    1    1 
## 1296 1297 1298 1299 1300 1301 1302 1304 1305 1306 1307 1308 1309 1310 1311 1312 
##    2    2    2    1    1    1    1    2    2    2    2    1    1    1    1    1 
## 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 
##    1    2    1    1    2    1    1    1    1    2    1    1    1    2    1    2 
## 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 
##    2    2    2    3    2    3    1    2    3    3    3    1    1    1    1    1 
## 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 
##    2    1    1    1    1    1    1    1    1    1    1    1    1    1    1    1 
## 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 
##    1    1    1    1    1    1    1    1    2    1    1    3    3    2    2    3 
## 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 
##    3    3    3    3    2    1    1    3    1    3    1    2    2    2    2    2 
## 1393 1394 1395 1396 1397 1398 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 
##    2    2    2    3    2    3    1    3    2    3    2    2    1    1    2    1 
## 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 
##    2    1    2    1    1    2    2    2    2    1    2    1    2    2    2    2 
## 1426 1427 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 
##    2    1    3    3    3    3    2    3    3    1    2    2    2    2    2    2 
## 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 
##    1    2    2    2    2    2    2    2    3    2    1    1    2    2    1    1 
## 
## Within cluster sum of squares by cluster:
## [1] 413 335 334
##  (between_SS / total_SS =  60.6 %)
## 
## Available components:
## 
##  [1] "cluster"      "centers"      "totss"        "withinss"     "tot.withinss"
##  [6] "betweenss"    "size"         "iter"         "ifault"       "crit"        
## [11] "bestk"
#obtaining distance matrix
dist.all <- dist(dailyscale[,c("lteq","posaff")],method="euclidean",diag=TRUE,upper=FALSE)
#obtaining metrics
cluster.stats(dist.all,clustering=model$cluster)
## $n
## [1] 1376
## 
## $cluster.number
## [1] 20
## 
## $cluster.size
##  [1]  66  49  94  43  32 100  62  16  25 118 116  39  12  63 110  76  91  53 129
## [20]  82
## 
## $min.cluster.size
## [1] 12
## 
## $noisen
## [1] 0
## 
## $diameter
##  [1] 1.480 1.480 0.858 1.251 2.347 0.883 1.482 1.667 1.947 1.028 1.057 1.445
## [13] 2.432 1.242 0.976 0.990 1.021 1.538 0.927 0.937
## 
## $average.distance
##  [1] 0.601 0.507 0.353 0.434 0.785 0.353 0.523 0.673 0.699 0.421 0.406 0.566
## [13] 1.154 0.525 0.364 0.458 0.402 0.465 0.380 0.354
## 
## $median.distance
##  [1] 0.578 0.454 0.340 0.411 0.665 0.340 0.488 0.542 0.678 0.396 0.394 0.545
## [13] 1.034 0.499 0.364 0.454 0.394 0.454 0.364 0.340
## 
## $separation
##  [1] 0.0960 0.0909 0.0909 0.0960 0.1322 0.0682 0.0909 0.1818 0.1322 0.0909
## [11] 0.0909 0.0909 0.3019 0.0960 0.0682 0.0909 0.0909 0.0909 0.0909 0.0909
## 
## $average.toother
##  [1] 2.27 2.21 1.79 1.95 3.10 1.40 2.44 2.75 2.61 1.77 1.47 2.13 3.52 1.86 1.38
## [16] 1.75 1.65 2.17 1.61 1.64
## 
## $separation.matrix
##        [,1]   [,2]   [,3]  [,4]  [,5]   [,6]   [,7]  [,8]  [,9]  [,10]  [,11]
##  [1,] 0.000 1.9755 1.8789 0.206 0.132 0.9975 2.4495 0.617 0.132 1.9310 0.0960
##  [2,] 1.975 0.0000 2.0807 1.122 3.040 1.6132 0.1919 0.998 2.947 0.5518 1.0403
##  [3,] 1.879 2.0807 0.0000 1.784 2.687 0.0909 1.9086 2.878 1.786 0.9088 0.8921
##  [4,] 0.206 1.1218 1.7841 0.000 1.000 0.9416 1.8059 0.182 1.216 1.4422 0.0960
##  [5,] 0.132 3.0398 2.6868 1.000 0.000 1.8591 3.5925 1.439 0.132 3.0598 1.2324
##  [6,] 0.998 1.6132 0.0909 0.942 1.859 0.0000 1.6178 2.053 1.188 0.6166 0.0909
##  [7,] 2.450 0.1919 1.9086 1.806 3.592 1.6178 0.0000 2.023 3.368 0.0909 1.3911
##  [8,] 0.617 0.9975 2.8784 0.182 1.439 2.0532 2.0233 0.000 2.036 2.3315 1.1513
##  [9,] 0.132 2.9466 1.7860 1.216 0.132 1.1881 3.3685 2.036 0.000 2.5955 0.9274
## [10,] 1.931 0.5518 0.9088 1.442 3.060 0.6166 0.0909 2.331 2.596 0.0000 0.8494
## [11,] 0.096 1.0403 0.8921 0.096 1.232 0.0909 1.3911 1.151 0.927 0.8494 0.0000
## [12,] 0.927 2.7417 0.7335 1.618 1.299 0.5453 2.8762 2.671 0.264 1.8966 0.8180
## [13,] 0.302 2.2913 3.3596 0.425 0.411 2.5033 3.1777 0.464 1.657 3.0706 1.5728
## [14,] 0.904 0.1322 1.6138 0.132 1.980 0.9035 0.7889 0.488 1.890 0.8494 0.1818
## [15,] 1.149 0.9088 0.5781 0.583 2.264 0.0682 0.9483 1.539 1.789 0.0909 0.0909
## [16,] 0.096 2.0554 0.9639 0.636 0.773 0.1919 2.3339 1.644 0.192 1.4669 0.0909
## [17,] 1.335 0.0909 1.2752 0.725 2.485 0.7952 0.2123 1.546 2.244 0.0909 0.2643
## [18,] 1.963 2.7417 0.0909 2.178 2.482 0.5781 2.6356 3.300 1.442 1.6359 1.3211
## [19,] 1.823 1.3143 0.0909 1.509 2.761 0.0909 1.0906 2.548 2.043 0.0909 0.7676
## [20,] 1.116 2.2721 0.0909 1.281 1.823 0.0909 2.2559 2.390 0.937 1.2423 0.4111
##        [,12] [,13] [,14]  [,15]  [,16]  [,17]  [,18]  [,19]  [,20]
##  [1,] 0.9274 0.302 0.904 1.1492 0.0960 1.3353 1.9628 1.8232 1.1164
##  [2,] 2.7417 2.291 0.132 0.9088 2.0554 0.0909 2.7417 1.3143 2.2721
##  [3,] 0.7335 3.360 1.614 0.5781 0.9639 1.2752 0.0909 0.0909 0.0909
##  [4,] 1.6178 0.425 0.132 0.5829 0.6362 0.7249 2.1781 1.5094 1.2809
##  [5,] 1.2993 0.411 1.980 2.2640 0.7730 2.4850 2.4818 2.7611 1.8232
##  [6,] 0.5453 2.503 0.904 0.0682 0.1919 0.7952 0.5781 0.0909 0.0909
##  [7,] 2.8762 3.178 0.789 0.9483 2.3339 0.2123 2.6356 1.0906 2.2559
##  [8,] 2.6712 0.464 0.488 1.5392 1.6443 1.5460 3.2996 2.5481 2.3905
##  [9,] 0.2643 1.657 1.890 1.7890 0.1919 2.2435 1.4422 2.0427 0.9370
## [10,] 1.8966 3.071 0.849 0.0909 1.4669 0.0909 1.6359 0.0909 1.2423
## [11,] 0.8180 1.573 0.182 0.0909 0.0909 0.2643 1.3211 0.7676 0.4111
## [12,] 0.0000 2.539 1.909 1.2160 0.0909 1.9182 0.1919 1.1895 0.0909
## [13,] 2.5392 0.000 1.361 2.2145 1.7396 2.3029 3.5842 3.1555 2.6762
## [14,] 1.9086 1.361 0.000 0.1818 1.0709 0.0960 2.1780 1.1037 1.4667
## [15,] 1.2160 2.214 0.182 0.0000 0.6608 0.0909 1.1970 0.0909 0.7271
## [16,] 0.0909 1.740 1.071 0.6608 0.0000 1.2423 0.9056 1.0594 0.0960
## [17,] 1.9182 2.303 0.096 0.0909 1.2423 0.0000 1.9182 0.5379 1.4541
## [18,] 0.1919 3.584 2.178 1.1970 0.9056 1.9182 0.0000 0.8180 0.0909
## [19,] 1.1895 3.155 1.104 0.0909 1.0594 0.5379 0.8180 0.0000 0.4637
## [20,] 0.0909 2.676 1.467 0.7271 0.0960 1.4541 0.0909 0.4637 0.0000
## 
## $ave.between.matrix
##       [,1]  [,2]  [,3]  [,4] [,5]  [,6]  [,7] [,8] [,9] [,10] [,11] [,12] [,13]
##  [1,] 0.00 2.919 2.878 1.064 1.25 2.018 3.534 1.86 1.48 2.978 1.412 2.055  1.89
##  [2,] 2.92 0.000 2.821 2.000 4.01 2.339 0.919 2.15 3.94 1.403 2.015 3.595  3.50
##  [3,] 2.88 2.821 0.000 2.715 3.68 0.941 2.756 3.75 2.76 1.606 1.694 1.664  4.52
##  [4,] 1.06 2.000 2.715 0.000 2.09 1.834 2.665 1.20 2.27 2.317 1.088 2.464  1.97
##  [5,] 1.25 4.014 3.683 2.094 0.00 2.905 4.638 2.68 1.38 4.037 2.421 2.442  2.07
##  [6,] 2.02 2.339 0.941 1.834 2.90 0.000 2.522 2.90 2.17 1.484 0.833 1.388  3.64
##  [7,] 3.53 0.919 2.756 2.665 4.64 2.522 0.000 2.92 4.40 1.197 2.430 3.853  4.26
##  [8,] 1.86 2.148 3.755 1.196 2.68 2.904 2.917 0.00 3.23 3.004 2.157 3.582  1.63
##  [9,] 1.48 3.937 2.762 2.269 1.38 2.173 4.398 3.23 0.00 3.541 2.016 1.330  3.04
## [10,] 2.98 1.403 1.606 2.317 4.04 1.484 1.197 3.00 3.54 0.000 1.668 2.809  4.16
## [11,] 1.41 2.015 1.694 1.088 2.42 0.833 2.430 2.16 2.02 1.668 0.000 1.694  2.90
## [12,] 2.05 3.595 1.664 2.464 2.44 1.388 3.853 3.58 1.33 2.809 1.694 0.000  3.83
## [13,] 1.89 3.501 4.523 1.970 2.07 3.636 4.261 1.63 3.04 4.159 2.904 3.832  0.00
## [14,] 1.89 1.161 2.552 0.994 2.97 1.806 1.811 1.43 2.98 1.673 1.220 2.847  2.63
## [15,] 2.17 1.640 1.325 1.649 3.20 0.781 1.824 2.56 2.70 0.912 0.857 2.072  3.53
## [16,] 1.29 2.886 1.758 1.586 1.98 1.041 3.270 2.70 1.26 2.375 0.949 0.974  3.05
## [17,] 2.50 0.935 1.974 1.718 3.59 1.505 1.159 2.32 3.29 0.788 1.330 2.796  3.52
## [18,] 2.96 3.545 0.881 3.059 3.55 1.357 3.553 4.17 2.45 2.403 2.062 1.249  4.71
## [19,] 2.78 2.150 0.766 2.389 3.73 0.896 2.059 3.32 3.00 0.927 1.457 2.084  4.26
## [20,] 2.15 2.890 0.885 2.199 2.87 0.637 3.050 3.31 1.94 1.965 1.219 0.951  3.88
##       [,14] [,15] [,16] [,17] [,18] [,19] [,20]
##  [1,] 1.889 2.174 1.291 2.496 2.959 2.782 2.150
##  [2,] 1.161 1.640 2.886 0.935 3.545 2.150 2.890
##  [3,] 2.552 1.325 1.758 1.974 0.881 0.766 0.885
##  [4,] 0.994 1.649 1.586 1.718 3.059 2.389 2.199
##  [5,] 2.969 3.203 1.978 3.591 3.548 3.731 2.869
##  [6,] 1.806 0.781 1.041 1.505 1.357 0.896 0.637
##  [7,] 1.811 1.824 3.270 1.159 3.553 2.059 3.050
##  [8,] 1.430 2.557 2.697 2.323 4.169 3.321 3.313
##  [9,] 2.976 2.699 1.256 3.291 2.448 3.004 1.938
## [10,] 1.673 0.912 2.375 0.788 2.403 0.927 1.965
## [11,] 1.220 0.857 0.949 1.330 2.062 1.457 1.219
## [12,] 2.847 2.072 0.974 2.796 1.249 2.084 0.951
## [13,] 2.630 3.535 3.050 3.518 4.715 4.263 3.882
## [14,] 0.000 1.291 2.035 1.014 3.110 2.032 2.313
## [15,] 1.291 0.000 1.543 0.819 1.968 0.829 1.307
## [16,] 2.035 1.543 0.000 2.168 1.742 1.870 0.971
## [17,] 1.014 0.819 2.168 0.000 2.687 1.332 2.050
## [18,] 3.110 1.968 1.742 2.687 0.000 1.541 0.925
## [19,] 2.032 0.829 1.870 1.332 1.541 0.000 1.220
## [20,] 2.313 1.307 0.971 2.050 0.925 1.220 0.000
## 
## $average.between
## [1] 1.84
## 
## $average.within
## [1] 0.449
## 
## $n.between
## [1] 887420
## 
## $n.within
## [1] 58580
## 
## $max.diameter
## [1] 2.43
## 
## $min.separation
## [1] 0.0682
## 
## $within.cluster.ss
## [1] 186
## 
## $clus.avg.silwidths
##     1     2     3     4     5     6     7     8     9    10    11    12    13 
## 0.299 0.339 0.428 0.457 0.277 0.320 0.373 0.391 0.290 0.357 0.378 0.261 0.178 
##    14    15    16    17    18    19    20 
## 0.316 0.369 0.359 0.338 0.374 0.356 0.363 
## 
## $avg.silwidth
## [1] 0.353
## 
## $g2
## NULL
## 
## $g3
## NULL
## 
## $pearsongamma
## [1] 0.358
## 
## $dunn
## [1] 0.028
## 
## $dunn2
## [1] 0.552
## 
## $entropy
## [1] 2.86
## 
## $wb.ratio
## [1] 0.243
## 
## $ch
## [1] 985
## 
## $cwidegap
##  [1] 0.206 0.454 0.288 0.212 0.815 0.192 0.288 0.678 1.028 0.288 0.182 0.464
## [13] 0.667 0.227 0.192 0.132 0.192 0.681 0.288 0.192
## 
## $widestgap
## [1] 1.03
## 
## $sindex
## [1] 0.0901
## 
## $corrected.rand
## NULL
## 
## $vi
## NULL
#library(clusterCrit)
#running a cluster analysis
model <- kmeans(dailyscale[,c("lteq","posaff")], centers=4)
#calculating various internal clustering validation or quality criteria
ic <- intCriteria(traj=as.matrix(dailyscale[,c("lteq","posaff")]), part=model$cluster, crit="all")
ic
## $ball_hall
## [1] 0.715
## 
## $banfeld_raftery
## [1] -703
## 
## $c_index
## [1] 0.114
## 
## $calinski_harabasz
## [1] 975
## 
## $davies_bouldin
## [1] 0.968
## 
## $det_ratio
## [1] 10.7
## 
## $dunn
## [1] 0.0174
## 
## $gamma
## [1] 0.718
## 
## $g_plus
## [1] 0.0556
## 
## $gdi11
## [1] 0.0174
## 
## $gdi12
## [1] 0.133
## 
## $gdi13
## [1] 0.0469
## 
## $gdi21
## [1] 0.683
## 
## $gdi22
## [1] 5.24
## 
## $gdi23
## [1] 1.84
## 
## $gdi31
## [1] 0.274
## 
## $gdi32
## [1] 2.1
## 
## $gdi33
## [1] 0.739
## 
## $gdi41
## [1] 0.225
## 
## $gdi42
## [1] 1.72
## 
## $gdi43
## [1] 0.606
## 
## $gdi51
## [1] 0.119
## 
## $gdi52
## [1] 0.913
## 
## $gdi53
## [1] 0.321
## 
## $ksq_detw
## [1] 2799085
## 
## $log_det_ratio
## [1] 3257
## 
## $log_ss_ratio
## [1] 0.757
## 
## $mcclain_rao
## [1] 0.463
## 
## $pbm
## [1] 1.52
## 
## $point_biserial
## [1] -0.489
## 
## $ray_turi
## [1] 0.464
## 
## $ratkowsky_lance
## [1] 0.413
## 
## $scott_symons
## [1] -3555
## 
## $sd_scat
## [1] 0.379
## 
## $sd_dis
## [1] 1.63
## 
## $s_dbw
## [1] 5.12
## 
## $silhouette
## [1] 0.343
## 
## $tau
## [1] 0.451
## 
## $trace_w
## [1] 878
## 
## $trace_wib
## [1] 4.82
## 
## $wemmert_gancarski
## [1] 0.493
## 
## $xie_beni
## [1] 77.2
#kmeans with nstart = 1
km.res <- kmeans(dailyscale[,c("lteq","posaff")], centers=4, nstart = 1)
km.res$tot.withinss
## [1] 878
#kmeans with nstart = 25
km.res <- kmeans(dailyscale[,c("lteq","posaff")], centers=4, nstart = 25)
km.res$tot.withinss
## [1] 878
#kmeans with nstart = 50
km.res <- kmeans(dailyscale[,c("lteq","posaff")], centers=4, nstart = 50)
km.res$tot.withinss
## [1] 878
dailyscale.clus <- cbind(km.res$cluster,dailyscale)
names(dailyscale.clus)[1] <- "cluster"
head(dailyscale.clus[,c(1:4,6)],4)
##   cluster   id slphrs     weath    pss
## 1       4 1010 -0.662 -0.773250 -0.173
## 2       4 1011 -2.877 -0.000562  0.192
## 3       2 1012  0.999  0.772127  1.289
## 4       2 1013  0.168 -0.000562  0.558
library(tidyverse)

# Gather the data to 'long' format so the clustering variables are all in one column
#gather() has been replaced by pivot_longer()
longdata <- dailyscale.clus %>%
  pivot_longer(c(lteq, posaff), names_to = "variable", values_to = "value")

# Create the summary statistics seperately for cluster and variable (i.e. lteq, posaff)
summary <- longdata %>%
             group_by(cluster, variable) %>%
             summarise(mean = mean(value), se = sd(value) / length(value))
## `summarise()` has grouped output by 'cluster'. You can override using the
## `.groups` argument.
# Plot
ggplot(summary, aes(x = variable, y = mean, fill = variable)) + 
  geom_bar(stat = 'identity', position = 'dodge') +
  geom_errorbar(aes(ymin = mean - se, ymax = mean + se),                            
                  width = 0.2,
                  position = position_dodge(0.9)) +
  facet_wrap(~cluster) 

## Analyzing the Cluseters

fit1 <- aov(pss ~ factor(km.res$cluster), data=dailyscale.clus)
summary(fit1)
##                          Df Sum Sq Mean Sq F value Pr(>F)    
## factor(km.res$cluster)    3    247    82.3     100 <2e-16 ***
## Residuals              1372   1128     0.8                   
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
TukeyHSD(fit1) 
##   Tukey multiple comparisons of means
##     95% family-wise confidence level
## 
## Fit: aov(formula = pss ~ factor(km.res$cluster), data = dailyscale.clus)
## 
## $`factor(km.res$cluster)`
##         diff    lwr    upr p adj
## 2-1  0.48604  0.277  0.696 0.000
## 3-1  0.49370  0.281  0.706 0.000
## 4-1 -0.44387 -0.649 -0.239 0.000
## 3-2  0.00767 -0.163  0.179 0.999
## 4-2 -0.92990 -1.092 -0.768 0.000
## 4-3 -0.93757 -1.103 -0.772 0.000
## Hierarchical Clustering

dist.all <- daisy(dailyscale[,c("lteq","posaff")],metric="euclidean",stand=FALSE)
#loking at distances among first 5 persons
as.matrix(dist.all)[1:5,1:5]
##        1      2     3     4     5
## 1 0.0000 0.0909 1.091 1.548 0.849
## 2 0.0909 0.0000 1.181 1.639 0.892
## 3 1.0906 1.1815 0.000 0.464 1.057
## 4 1.5480 1.6387 0.464 0.000 1.463
## 5 0.8494 0.8921 1.057 1.463 0.000
# Compute Ward clusters for IGother
clusterward.papa <- agnes(dist.all, diss = TRUE, method = "ward")
# Plot
layout(matrix(1))
plot(clusterward.papa, which.plot = 2, main = "Ward clustering of PAPA")

wardcluster4 <- cutree(clusterward.papa, k = 4)
cluster.stats(dist.all, clustering=wardcluster4,
              silhouette = TRUE, sepindex = TRUE)
## $n
## [1] 1376
## 
## $cluster.number
## [1] 4
## 
## $cluster.size
## [1] 437 443 229 267
## 
## $min.cluster.size
## [1] 229
## 
## $noisen
## [1] 0
## 
## $diameter
## [1] 4.71 3.03 4.36 2.84
## 
## $average.distance
## [1] 1.071 0.873 1.291 0.876
## 
## $median.distance
## [1] 0.964 0.858 1.204 0.815
## 
## $separation
## [1] 0.0909 0.0909 0.0909 0.0909
## 
## $average.toother
## [1] 1.78 1.97 2.40 2.16
## 
## $separation.matrix
##        [,1]   [,2]   [,3]   [,4]
## [1,] 0.0000 0.0909 0.0909 0.0909
## [2,] 0.0909 0.0000 0.0960 0.0909
## [3,] 0.0909 0.0960 0.0000 1.6532
## [4,] 0.0909 0.0909 1.6532 0.0000
## 
## $ave.between.matrix
##      [,1] [,2] [,3] [,4]
## [1,] 0.00 1.72 2.02 1.66
## [2,] 1.72 0.00 2.27 2.11
## [3,] 2.02 2.27 0.00 3.23
## [4,] 1.66 2.11 3.23 0.00
## 
## $average.between
## [1] 2.04
## 
## $average.within
## [1] 1.01
## 
## $n.between
## [1] 691214
## 
## $n.within
## [1] 254786
## 
## $max.diameter
## [1] 4.71
## 
## $min.separation
## [1] 0.0909
## 
## $within.cluster.ss
## [1] 948
## 
## $clus.avg.silwidths
##     1     2     3     4 
## 0.178 0.453 0.283 0.452 
## 
## $avg.silwidth
## [1] 0.338
## 
## $g2
## NULL
## 
## $g3
## NULL
## 
## $pearsongamma
## [1] 0.483
## 
## $dunn
## [1] 0.0193
## 
## $dunn2
## [1] 1.28
## 
## $entropy
## [1] 1.35
## 
## $wb.ratio
## [1] 0.494
## 
## $ch
## [1] 869
## 
## $cwidegap
## [1] 0.725 0.617 0.909 0.454
## 
## $widestgap
## [1] 0.909
## 
## $sindex
## [1] 0.129
## 
## $corrected.rand
## NULL
## 
## $vi
## NULL
## K-medoids

# Compute PAM clustering solution for k=4
clusterpam.papa <- pam(dist.all, k=4, diss = TRUE)
clusterpam.papa
## Medoids:
##      ID         
## [1,] "129" "154"
## [2,] "108" "130"
## [3,] "676" "739"
## [4,] "233" "262"
## Clustering vector:
##    1    2    3    4    5    6    7    9   10   11   13   14   15   17   18   19 
##    1    1    2    2    3    3    3    2    2    2    2    2    4    2    1    2 
##   20   21   22   23   27   28   29   30   31   32   37   38   39   40   41   42 
##    1    4    4    2    4    4    4    4    2    1    1    1    2    2    4    2 
##   43   44   47   48   49   51   52   53   54   55   56   57   58   59   60   61 
##    2    1    1    1    1    1    2    1    1    4    3    4    4    4    4    4 
##   62   63   64   66   67   68   70   71   72   73   74   75   76   77   78   79 
##    3    1    2    3    4    1    2    2    2    1    2    2    1    1    2    1 
##   81   84   85   86   87   88   89   90   91   92   93   95   96   97   98   99 
##    1    1    4    1    1    2    2    3    3    3    3    2    2    2    2    3 
##  101  102  103  105  106  107  108  110  111  112  113  114  115  116  117  118 
##    3    3    2    4    3    3    3    2    3    3    3    3    3    3    3    3 
##  119  120  121  122  123  124  125  126  127  128  129  130  131  132  133  134 
##    3    4    1    4    4    4    4    4    1    2    2    2    2    1    2    2 
##  135  136  137  138  140  141  143  144  145  146  147  149  150  151  152  153 
##    2    3    3    2    3    1    3    3    1    3    3    3    3    3    4    3 
##  154  155  156  157  158  159  160  161  162  163  164  165  166  167  168  169 
##    1    1    1    3    3    2    2    2    2    2    2    2    1    1    2    2 
##  170  171  172  173  174  175  176  177  178  179  180  181  182  183  184  185 
##    1    1    1    4    1    4    4    4    4    1    1    1    2    2    4    1 
##  186  187  188  189  190  191  192  193  194  196  197  198  199  201  202  203 
##    1    3    3    3    1    3    3    4    4    2    1    1    1    1    3    3 
##  204  205  206  208  209  210  211  212  213  214  215  216  217  218  219  220 
##    2    2    3    3    3    1    2    2    1    1    1    1    2    4    4    4 
##  221  222  223  224  225  226  228  229  230  231  232  233  234  235  236  237 
##    4    3    4    4    4    2    2    2    4    4    1    3    1    1    1    4 
##  238  239  240  241  242  243  244  245  246  247  248  249  250  251  252  253 
##    1    1    1    4    1    1    2    3    3    1    3    2    3    1    3    3 
##  254  255  256  257  258  259  260  261  262  263  264  265  266  267  268  269 
##    4    3    3    3    2    1    2    2    4    1    1    2    1    1    1    1 
##  270  271  272  273  274  275  276  277  278  279  280  281  282  283  285  286 
##    3    1    1    1    1    2    1    1    1    1    1    1    4    1    4    4 
##  287  288  289  290  291  292  293  294  295  296  297  298  299  300  301  302 
##    4    1    2    1    1    1    4    1    4    2    2    2    1    1    1    4 
##  303  304  305  306  307  308  309  312  313  314  315  316  317  318  319  320 
##    1    2    2    2    1    2    1    1    2    2    1    1    3    4    4    2 
##  321  323  324  325  326  327  328  329  330  331  332  333  334  335  343  344 
##    2    2    2    2    2    2    2    2    2    2    2    2    2    2    4    2 
##  345  346  347  348  349  350  352  353  354  355  356  358  359  360  361  364 
##    1    1    1    1    1    2    1    2    1    1    1    1    1    2    2    3 
##  365  366  367  368  369  370  371  372  373  374  376  377  378  379  380  381 
##    3    3    2    1    1    1    1    1    1    1    4    4    4    2    2    4 
##  382  383  384  385  386  387  388  389  390  391  392  393  394  395  396  397 
##    4    1    4    1    3    1    1    1    1    1    3    3    4    4    3    3 
##  398  399  400  401  402  403  404  405  406  407  408  409  410  411  412  413 
##    3    3    3    1    4    3    3    1    3    4    4    1    1    4    4    4 
##  414  415  416  417  418  419  422  423  424  425  426  427  428  429  430  431 
##    4    2    1    2    2    2    1    2    3    1    3    3    3    3    3    2 
##  432  433  434  435  436  437  438  439  441  442  443  444  445  446  447  448 
##    2    2    1    1    1    1    1    3    2    1    1    4    3    3    2    2 
##  449  450  451  452  453  454  455  456  457  458  459  460  461  462  463  464 
##    2    2    2    1    2    2    4    4    4    4    4    4    4    4    1    2 
##  465  466  467  468  469  470  471  472  473  474  475  476  477  478  479  480 
##    1    1    1    1    1    4    2    1    3    3    1    1    1    4    4    4 
##  481  483  485  486  487  488  489  490  491  492  493  494  495  496  497  498 
##    2    4    2    1    2    4    4    1    4    4    4    2    1    2    1    1 
##  499  500  501  502  503  504  505  506  507  508  509  510  511  512  513  514 
##    4    4    1    3    1    4    4    4    4    1    2    2    2    2    2    2 
##  515  516  517  518  519  520  521  522  523  524  525  526  527  528  529  530 
##    4    1    2    3    2    2    3    2    3    3    4    1    1    2    3    1 
##  531  533  534  535  536  537  538  539  540  541  542  543  544  545  546  548 
##    3    4    3    3    3    4    4    4    4    4    4    4    2    3    2    3 
##  549  550  551  552  553  554  555  556  557  558  559  560  561  562  563  564 
##    3    2    2    1    3    3    3    3    4    3    3    2    3    4    1    2 
##  565  566  567  568  569  570  571  572  573  574  575  576  577  578  579  580 
##    3    4    1    2    2    2    2    2    2    2    2    4    3    3    3    3 
##  581  582  583  584  585  586  587  588  589  590  591  592  593  594  595  596 
##    4    4    4    1    2    1    1    1    1    1    1    2    1    4    4    1 
##  597  598  599  601  602  603  604  605  606  607  609  610  611  612  613  614 
##    1    4    4    1    1    4    1    4    4    4    2    1    1    2    1    4 
##  615  616  617  618  619  620  621  622  623  624  625  626  628  629  630  631 
##    1    2    1    1    2    2    1    4    1    2    2    1    2    2    1    1 
##  632  633  634  635  636  637  638  639  640  641  642  643  644  645  646  647 
##    4    1    4    4    1    2    4    4    1    3    1    4    4    4    4    4 
##  648  649  650  651  652  653  654  655  656  657  658  659  660  661  662  663 
##    4    1    1    4    4    4    1    3    3    4    4    4    4    4    4    4 
##  664  665  666  667  668  669  670  671  672  673  674  675  676  677  678  679 
##    3    3    3    3    3    3    3    3    3    3    3    2    1    4    3    2 
##  680  681  682  684  685  686  687  688  689  690  691  692  693  694  696  697 
##    2    2    1    4    1    2    2    3    3    2    2    2    3    3    2    4 
##  698  699  700  701  702  703  704  705  706  707  708  709  710  711  712  713 
##    4    2    4    4    4    3    3    3    3    3    1    4    3    4    1    4 
##  714  715  716  717  719  720  721  722  723  724  725  726  727  728  731  735 
##    1    1    1    1    4    1    1    4    4    4    4    4    3    3    3    1 
##  736  737  738  739  740  741  742  743  744  745  746  747  748  749  750  751 
##    3    1    2    3    4    4    1    3    3    3    2    3    1    3    2    2 
##  752  753  754  755  757  758  759  760  761  762  763  764  765  766  767  768 
##    1    4    3    1    4    1    1    4    4    1    2    1    2    2    1    1 
##  769  770  771  772  773  774  775  776  777  778  779  780  781  782  783  784 
##    1    1    2    1    1    1    3    1    3    4    4    4    4    4    4    4 
##  785  786  787  788  789  790  791  792  793  794  795  796  797  798  799  800 
##    4    1    4    4    1    1    4    4    3    3    3    4    3    2    3    3 
##  801  802  803  804  805  806  807  808  809  810  811  812  813  814  815  816 
##    3    3    3    4    3    4    2    2    2    2    1    1    1    4    4    4 
##  817  819  820  821  822  823  824  825  826  827  828  829  830  831  832  833 
##    1    4    4    1    4    2    1    1    4    2    1    3    4    4    2    2 
##  834  835  836  837  838  839  840  841  842  843  844  845  846  847  848  849 
##    4    3    1    2    1    2    1    1    1    2    3    4    1    1    3    1 
##  850  851  852  853  854  855  856  857  858  859  860  861  862  863  864  866 
##    1    4    1    1    3    2    2    2    3    2    3    2    3    3    3    3 
##  867  868  869  871  872  873  874  875  876  877  878  879  880  881  882  883 
##    3    3    3    3    3    3    3    4    1    3    1    4    1    1    1    1 
##  884  885  886  887  888  889  890  891  892  893  894  895  896  897  898  899 
##    4    2    1    4    4    4    1    4    1    1    1    1    1    1    1    1 
##  900  901  902  903  904  905  906  907  908  909  910  911  912  913  914  915 
##    1    1    1    1    2    1    1    1    1    3    4    1    4    4    3    3 
##  916  917  918  919  920  921  922  923  924  925  926  927  928  929  930  931 
##    4    3    2    1    2    1    1    4    1    4    2    2    1    1    1    1 
##  932  933  934  935  936  937  938  940  942  943  944  945  946  947  948  949 
##    1    2    3    3    3    3    3    2    2    2    1    2    4    4    1    1 
##  950  951  952  953  956  957  958  959  960  961  962  963  964  965  966  967 
##    3    1    1    1    4    1    2    1    2    1    1    1    1    1    3    3 
##  968  969  970  971  972  973  974  976  977  978  979  980  982  983  984  985 
##    2    4    4    3    3    3    4    2    1    3    4    4    2    2    2    1 
##  986  987  988  989  990  991  992  993  994  995  996  997  998  999 1000 1001 
##    4    3    4    1    1    3    1    2    3    1    3    1    4    2    3    4 
## 1002 1003 1004 1005 1006 1007 1008 1009 1011 1012 1013 1014 1015 1016 1017 1018 
##    3    3    1    3    1    1    1    1    4    4    1    4    1    3    3    3 
## 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 
##    2    2    2    4    3    4    1    3    3    4    1    1    1    4    4    1 
## 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 
##    4    4    4    2    2    2    2    2    2    2    2    2    2    2    2    2 
## 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1064 1065 1066 1067 
##    3    2    3    2    2    1    1    1    1    1    1    1    3    4    1    2 
## 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 
##    2    1    2    3    2    3    4    3    3    2    2    2    2    1    1    1 
## 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 
##    1    2    2    2    2    2    2    1    2    2    2    2    2    2    2    2 
## 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 
##    2    2    4    2    1    4    1    1    1    2    3    2    2    2    2    2 
## 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 
##    2    2    1    1    3    3    1    3    2    1    1    1    2    2    3    3 
## 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 
##    3    2    2    3    2    3    3    3    3    3    1    2    2    1    1    2 
## 1148 1149 1150 1151 1152 1153 1154 1156 1157 1158 1160 1161 1162 1163 1164 1165 
##    2    2    2    2    4    1    2    4    2    4    2    1    1    1    4    4 
## 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 
##    2    3    3    4    4    1    3    2    3    3    4    1    1    3    3    2 
## 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 
##    4    2    2    4    1    1    1    4    1    3    3    1    2    3    3    3 
## 1198 1199 1200 1201 1202 1203 1204 1205 1207 1208 1209 1210 1211 1212 1213 1215 
##    1    2    2    2    1    2    4    1    2    4    2    1    2    2    2    1 
## 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 
##    1    1    2    2    1    2    4    1    1    2    2    1    1    4    3    3 
## 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 
##    3    3    3    3    4    4    2    2    1    2    2    1    4    4    1    1 
## 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 
##    2    3    4    2    3    1    3    2    2    3    3    3    3    3    2    1 
## 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 
##    2    2    1    1    4    1    2    1    3    3    4    1    2    3    2    2 
## 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 
##    1    2    1    4    1    1    1    1    4    4    1    1    2    2    2    2 
## 1296 1297 1298 1299 1300 1301 1302 1304 1305 1306 1307 1308 1309 1310 1311 1312 
##    4    4    4    2    1    2    2    1    4    4    4    2    1    1    1    2 
## 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 
##    1    1    2    1    4    2    1    2    1    4    1    2    1    4    1    4 
## 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 
##    4    4    1    3    4    3    2    1    3    3    4    2    2    2    2    2 
## 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 
##    1    1    2    2    2    2    2    2    2    2    1    2    2    2    2    2 
## 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 
##    1    2    2    2    2    2    2    2    4    2    2    3    3    1    4    3 
## 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 
##    3    3    3    3    1    2    2    3    2    3    2    1    4    4    4    4 
## 1393 1394 1395 1396 1397 1398 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 
##    4    4    4    3    4    3    2    3    4    3    4    1    1    2    4    1 
## 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 
##    1    1    1    2    2    4    1    1    4    1    1    2    1    4    4    4 
## 1426 1427 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 
##    4    1    3    3    3    3    4    3    3    1    1    4    4    4    1    4 
## 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 
##    1    1    4    4    4    4    4    1    3    1    2    2    4    4    1    1 
## Objective function:
## build  swap 
## 0.718 0.705 
## 
## Available components:
## [1] "medoids"    "id.med"     "clustering" "objective"  "isolation" 
## [6] "clusinfo"   "silinfo"    "diss"       "call"
#Checking length
pamcluster <- clusterpam.papa$clustering
length(pamcluster)
## [1] 1376
#binding to originaldata
dailyscale.pam <- cbind(dailyscale,pamcluster)
#plotting clustered data points 
ggplot(dailyscale.pam,aes(x=lteq,y=posaff)) +
  geom_point(alpha=.6, color=factor(pamcluster))

pamauto <- pamk(dist.all,krange=2:10,criterion="asw", usepam=TRUE,
                scaling=FALSE, alpha=0.001, diss=TRUE,
                critout=FALSE, ns=10, seed=NULL)
pamauto
## $pamobject
## Medoids:
##      ID         
## [1,] "598" "653"
## [2,] "63"  "78" 
## [3,] "738" "802"
## Clustering vector:
##    1    2    3    4    5    6    7    9   10   11   13   14   15   17   18   19 
##    1    1    2    2    3    3    3    2    2    2    2    2    1    2    2    2 
##   20   21   22   23   27   28   29   30   31   32   37   38   39   40   41   42 
##    1    1    1    2    1    1    1    1    2    2    2    2    2    2    1    2 
##   43   44   47   48   49   51   52   53   54   55   56   57   58   59   60   61 
##    2    1    2    2    2    2    2    2    2    1    3    1    1    1    1    1 
##   62   63   64   66   67   68   70   71   72   73   74   75   76   77   78   79 
##    3    2    3    3    1    3    2    2    2    2    2    2    2    1    2    3 
##   81   84   85   86   87   88   89   90   91   92   93   95   96   97   98   99 
##    2    1    1    1    2    2    2    3    3    3    3    2    2    2    2    3 
##  101  102  103  105  106  107  108  110  111  112  113  114  115  116  117  118 
##    3    3    2    1    3    3    3    2    3    3    3    3    3    3    3    3 
##  119  120  121  122  123  124  125  126  127  128  129  130  131  132  133  134 
##    3    1    1    1    1    1    1    1    1    2    2    2    2    2    2    2 
##  135  136  137  138  140  141  143  144  145  146  147  149  150  151  152  153 
##    2    3    3    2    3    3    3    3    3    3    3    3    3    3    1    3 
##  154  155  156  157  158  159  160  161  162  163  164  165  166  167  168  169 
##    2    2    2    3    3    2    2    2    2    2    2    2    2    1    2    2 
##  170  171  172  173  174  175  176  177  178  179  180  181  182  183  184  185 
##    1    2    3    1    1    1    1    1    1    1    1    2    3    3    1    3 
##  186  187  188  189  190  191  192  193  194  196  197  198  199  201  202  203 
##    2    3    3    3    1    3    3    1    1    2    2    2    2    3    3    3 
##  204  205  206  208  209  210  211  212  213  214  215  216  217  218  219  220 
##    2    2    3    3    3    2    2    2    2    2    2    1    2    1    1    1 
##  221  222  223  224  225  226  228  229  230  231  232  233  234  235  236  237 
##    1    3    1    1    3    2    2    2    1    1    2    3    2    2    1    1 
##  238  239  240  241  242  243  244  245  246  247  248  249  250  251  252  253 
##    2    1    1    1    3    2    2    3    3    2    3    2    3    1    3    3 
##  254  255  256  257  258  259  260  261  262  263  264  265  266  267  268  269 
##    1    3    3    3    2    2    2    2    1    2    2    2    2    1    2    1 
##  270  271  272  273  274  275  276  277  278  279  280  281  282  283  285  286 
##    3    2    2    2    2    2    1    1    1    2    1    1    1    1    1    1 
##  287  288  289  290  291  292  293  294  295  296  297  298  299  300  301  302 
##    1    1    2    1    1    1    1    1    1    2    2    2    1    1    2    1 
##  303  304  305  306  307  308  309  312  313  314  315  316  317  318  319  320 
##    3    2    2    2    2    2    1    2    2    2    2    3    3    1    1    2 
##  321  323  324  325  326  327  328  329  330  331  332  333  334  335  343  344 
##    2    2    2    2    2    2    2    3    2    2    2    2    2    2    1    2 
##  345  346  347  348  349  350  352  353  354  355  356  358  359  360  361  364 
##    1    2    1    2    2    2    2    2    2    1    1    1    1    2    3    3 
##  365  366  367  368  369  370  371  372  373  374  376  377  378  379  380  381 
##    3    3    2    2    2    2    3    2    2    3    1    1    1    2    2    1 
##  382  383  384  385  386  387  388  389  390  391  392  393  394  395  396  397 
##    1    2    3    2    3    2    2    1    1    3    3    3    1    1    3    3 
##  398  399  400  401  402  403  404  405  406  407  408  409  410  411  412  413 
##    3    3    3    1    1    3    3    1    3    1    1    1    2    1    1    1 
##  414  415  416  417  418  419  422  423  424  425  426  427  428  429  430  431 
##    1    2    2    2    2    2    1    2    3    3    3    3    3    3    3    2 
##  432  433  434  435  436  437  438  439  441  442  443  444  445  446  447  448 
##    2    2    2    2    3    1    1    3    2    2    3    1    3    3    2    2 
##  449  450  451  452  453  454  455  456  457  458  459  460  461  462  463  464 
##    2    2    2    2    2    2    1    1    1    1    3    1    1    1    2    2 
##  465  466  467  468  469  470  471  472  473  474  475  476  477  478  479  480 
##    1    1    2    2    2    1    2    2    3    3    2    1    1    1    1    1 
##  481  483  485  486  487  488  489  490  491  492  493  494  495  496  497  498 
##    2    1    2    2    2    1    1    1    1    1    1    2    1    2    1    1 
##  499  500  501  502  503  504  505  506  507  508  509  510  511  512  513  514 
##    1    1    2    3    1    1    1    1    1    2    2    2    2    2    2    2 
##  515  516  517  518  519  520  521  522  523  524  525  526  527  528  529  530 
##    1    1    3    3    2    2    3    2    3    3    1    1    1    2    3    3 
##  531  533  534  535  536  537  538  539  540  541  542  543  544  545  546  548 
##    3    1    3    3    3    1    1    1    1    1    1    1    2    3    2    3 
##  549  550  551  552  553  554  555  556  557  558  559  560  561  562  563  564 
##    3    3    3    2    3    3    3    3    1    3    3    2    3    1    1    2 
##  565  566  567  568  569  570  571  572  573  574  575  576  577  578  579  580 
##    3    1    1    2    2    2    2    2    2    2    2    1    3    3    3    3 
##  581  582  583  584  585  586  587  588  589  590  591  592  593  594  595  596 
##    1    1    1    1    2    2    1    1    2    1    1    2    1    1    1    2 
##  597  598  599  601  602  603  604  605  606  607  609  610  611  612  613  614 
##    1    1    1    2    1    1    2    1    1    1    2    2    2    2    1    1 
##  615  616  617  618  619  620  621  622  623  624  625  626  628  629  630  631 
##    2    2    2    2    2    2    1    1    1    2    2    2    2    2    2    2 
##  632  633  634  635  636  637  638  639  640  641  642  643  644  645  646  647 
##    1    1    1    1    1    2    1    1    2    3    2    1    1    1    1    1 
##  648  649  650  651  652  653  654  655  656  657  658  659  660  661  662  663 
##    1    2    1    1    1    1    3    3    3    1    1    1    1    1    1    1 
##  664  665  666  667  668  669  670  671  672  673  674  675  676  677  678  679 
##    3    3    3    3    3    3    3    3    3    3    3    2    2    1    3    2 
##  680  681  682  684  685  686  687  688  689  690  691  692  693  694  696  697 
##    2    2    2    1    1    2    2    3    3    2    2    2    3    3    2    1 
##  698  699  700  701  702  703  704  705  706  707  708  709  710  711  712  713 
##    1    2    1    1    1    3    3    3    3    3    1    1    3    1    1    1 
##  714  715  716  717  719  720  721  722  723  724  725  726  727  728  731  735 
##    2    1    1    1    1    1    3    1    1    1    1    1    3    3    3    2 
##  736  737  738  739  740  741  742  743  744  745  746  747  748  749  750  751 
##    3    2    3    3    1    1    3    3    3    3    2    3    1    3    2    2 
##  752  753  754  755  757  758  759  760  761  762  763  764  765  766  767  768 
##    1    1    3    2    1    2    1    1    1    2    2    1    2    2    2    2 
##  769  770  771  772  773  774  775  776  777  778  779  780  781  782  783  784 
##    2    1    2    2    1    1    3    1    3    1    1    1    1    1    1    1 
##  785  786  787  788  789  790  791  792  793  794  795  796  797  798  799  800 
##    1    1    1    1    2    2    1    1    3    3    3    1    3    2    3    3 
##  801  802  803  804  805  806  807  808  809  810  811  812  813  814  815  816 
##    3    3    3    1    3    1    2    2    2    2    2    2    2    1    1    1 
##  817  819  820  821  822  823  824  825  826  827  828  829  830  831  832  833 
##    2    1    1    1    1    2    2    2    1    2    1    3    1    1    2    2 
##  834  835  836  837  838  839  840  841  842  843  844  845  846  847  848  849 
##    1    3    1    3    2    2    1    2    2    2    3    1    1    1    3    2 
##  850  851  852  853  854  855  856  857  858  859  860  861  862  863  864  866 
##    2    1    2    1    3    2    2    3    3    2    3    2    3    3    3    3 
##  867  868  869  871  872  873  874  875  876  877  878  879  880  881  882  883 
##    3    3    3    3    3    3    3    1    1    3    1    1    2    1    2    1 
##  884  885  886  887  888  889  890  891  892  893  894  895  896  897  898  899 
##    1    2    2    1    1    1    2    1    2    2    2    3    2    2    1    2 
##  900  901  902  903  904  905  906  907  908  909  910  911  912  913  914  915 
##    2    2    2    2    2    1    1    1    2    3    1    3    1    1    3    3 
##  916  917  918  919  920  921  922  923  924  925  926  927  928  929  930  931 
##    1    3    2    3    3    3    1    1    2    1    2    2    1    2    2    2 
##  932  933  934  935  936  937  938  940  942  943  944  945  946  947  948  949 
##    1    2    3    3    3    3    3    2    2    2    2    2    1    1    1    2 
##  950  951  952  953  956  957  958  959  960  961  962  963  964  965  966  967 
##    3    3    2    1    1    1    2    2    2    1    1    1    1    2    3    3 
##  968  969  970  971  972  973  974  976  977  978  979  980  982  983  984  985 
##    2    1    1    3    3    3    1    2    2    3    1    1    2    2    2    1 
##  986  987  988  989  990  991  992  993  994  995  996  997  998  999 1000 1001 
##    1    3    1    1    3    3    2    2    3    3    3    1    1    3    3    1 
## 1002 1003 1004 1005 1006 1007 1008 1009 1011 1012 1013 1014 1015 1016 1017 1018 
##    3    3    3    3    1    2    2    2    1    1    2    1    3    3    3    3 
## 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 
##    2    2    2    1    3    1    3    3    3    1    2    1    1    1    1    1 
## 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 
##    1    1    1    2    2    2    2    2    2    2    2    3    2    2    2    2 
## 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1064 1065 1066 1067 
##    3    2    3    2    2    2    2    1    1    1    1    3    3    1    3    3 
## 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 
##    2    3    2    3    2    3    1    3    3    3    2    2    2    1    2    1 
## 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 
##    2    2    2    2    2    2    2    2    2    2    2    2    2    2    2    2 
## 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 
##    2    2    1    2    1    1    2    1    2    2    3    2    3    2    2    2 
## 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 
##    2    2    2    3    3    3    1    3    2    1    2    2    3    2    3    3 
## 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 
##    3    2    2    3    2    3    3    3    3    3    2    2    2    3    2    2 
## 1148 1149 1150 1151 1152 1153 1154 1156 1157 1158 1160 1161 1162 1163 1164 1165 
##    2    2    2    2    1    2    2    1    2    1    2    2    2    1    1    1 
## 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 
##    2    3    3    1    1    1    3    2    3    3    1    2    1    3    3    3 
## 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 
##    1    2    2    1    2    3    3    1    1    3    3    1    3    3    3    3 
## 1198 1199 1200 1201 1202 1203 1204 1205 1207 1208 1209 1210 1211 1212 1213 1215 
##    2    2    2    2    2    2    1    1    2    1    2    2    2    2    2    2 
## 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 
##    2    1    2    2    2    2    1    2    1    2    2    1    2    1    3    3 
## 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 
##    3    3    3    3    1    1    2    2    1    2    2    2    1    1    1    2 
## 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 
##    2    3    1    2    3    2    3    3    2    3    3    3    3    3    2    2 
## 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 
##    2    2    3    2    1    2    2    3    3    3    1    2    3    3    2    2 
## 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 
##    2    2    1    1    1    1    2    1    1    1    2    2    2    2    2    2 
## 1296 1297 1298 1299 1300 1301 1302 1304 1305 1306 1307 1308 1309 1310 1311 1312 
##    1    1    1    2    2    2    2    1    1    1    1    2    2    2    2    2 
## 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 
##    2    1    2    2    1    2    2    2    2    1    2    2    2    1    2    1 
## 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 
##    1    1    1    3    1    3    2    3    3    3    3    2    2    2    2    2 
## 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 
##    1    2    2    2    2    2    2    2    2    2    2    2    2    2    2    2 
## 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 
##    2    2    2    2    2    2    2    2    1    2    2    3    3    1    1    3 
## 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 
##    3    3    3    3    1    2    2    3    3    3    3    1    1    1    1    1 
## 1393 1394 1395 1396 1397 1398 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 
##    1    1    1    3    1    3    2    3    1    3    1    1    2    2    1    2 
## 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 
##    3    2    1    2    2    1    1    1    1    2    1    2    1    1    1    1 
## 1426 1427 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 
##    1    2    3    3    3    3    1    3    3    2    1    1    1    1    1    1 
## 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 
##    2    1    1    1    1    1    1    1    3    1    2    2    1    1    2    2 
## Objective function:
## build  swap 
## 0.850 0.787 
## 
## Available components:
## [1] "medoids"    "id.med"     "clustering" "objective"  "isolation" 
## [6] "clusinfo"   "silinfo"    "diss"       "call"      
## 
## $nc
## [1] 3
## 
## $crit
##  [1] 0.000 0.335 0.381 0.317 0.326 0.336 0.349 0.335 0.334 0.333
#Obtain medoids
pamauto$pamobject$id.med
## [1] 598  63 738
#binding new cluster assignment to originaldata
dailyscale.pam$pamnew <- pamauto$pamobject$clustering

#plotting clustered data points with the medoids
ggplot(dailyscale.pam,aes(x=lteq,y=posaff)) +
  geom_point(alpha=.6, color=factor(dailyscale.pam$pamnew)) +
  geom_point(data=dailyscale.pam[598,],aes(x=lteq,y=posaff),color=2,size=5,shape=18) +
  geom_point(data=dailyscale.pam[63,],aes(x=lteq,y=posaff),color=1,size=5,shape=18) +
  geom_point(data=dailyscale.pam[738,],aes(x=lteq,y=posaff),color=4,size=5,shape=18)

Example Big Five

The following chunk is just to demonstrate the data wrangling.

require(tidyverse)
dd <- read.csv2('http://e-scientifics.de/content/datasets/Big5_GEMI_R_recoded.csv') # read data, items already recoded
dd <- cbind(1:nrow(dd), dd)
colnames(dd)[1] <- "subj"
getwd()
readr::write_csv(dd, "big5_gemi.csv")

# Neuroticism
dd <- dplyr::rowwise(dd) %>% dplyr::mutate(neo_n = mean(c(neo_ffi_1_rec, neo_ffi_6, neo_ffi_11, neo_ffi_16_rec, neo_ffi_21, neo_ffi_26, neo_ffi_31_rec, neo_ffi_36, neo_ffi_41, neo_ffi_46_rec, neo_ffi_51, neo_ffi_56)))

# Extraversion
dd <- dplyr::rowwise(dd) %>% dplyr::mutate(neo_e = mean(c(neo_ffi_2, neo_ffi_7, neo_ffi_12_rec, neo_ffi_17, neo_ffi_22, neo_ffi_27_rec, neo_ffi_32, neo_ffi_37, neo_ffi_42_rec, neo_ffi_47, neo_ffi_52, neo_ffi_57_rec)))

# Openness to experience
dd <- dplyr::rowwise(dd) %>% dplyr::mutate(neo_o = mean(c(neo_ffi_3_rec, neo_ffi_8_rec, neo_ffi_13, neo_ffi_18_rec, neo_ffi_23_rec, neo_ffi_28, neo_ffi_33_rec, neo_ffi_38_rec, neo_ffi_43, neo_ffi_48_rec, neo_ffi_53, neo_ffi_58)))

# Agreeableness
dd <- dplyr::rowwise(dd) %>% dplyr::mutate(neo_a = mean(c(neo_ffi_4, neo_ffi_9_rec, neo_ffi_14_rec, neo_ffi_19, neo_ffi_24_rec, neo_ffi_29_rec, neo_ffi_34, neo_ffi_39_rec, neo_ffi_44_rec, neo_ffi_49, neo_ffi_54_rec, neo_ffi_59_rec)))

# Conscientiousness
dd <- dplyr::rowwise(dd) %>% dplyr::mutate(neo_c = mean(c(neo_ffi_5, neo_ffi_10, neo_ffi_15_rec, neo_ffi_20, neo_ffi_25, neo_ffi_30_rec, neo_ffi_35, neo_ffi_40, neo_ffi_45_rec, neo_ffi_50, neo_ffi_55_rec, neo_ffi_60)))

readr::write_csv(dd, "big5_gemi_scores.csv")

And now some clustering …

require(tidyverse)
dd <- readr::read_csv("http://md.psych.bio.uni-goettingen.de/mv/data/div/big5_gemi_scores.csv")
## Rows: 160 Columns: 68
## ── Column specification ────────────────────────────────────────────────────────
## Delimiter: ","
## dbl (68): subj, vpage, vpsex, neo_ffi_1_rec, neo_ffi_2, neo_ffi_3_rec, neo_f...
## 
## ℹ Use `spec()` to retrieve the full column specification for this data.
## ℹ Specify the column types or set `show_col_types = FALSE` to quiet this message.
# some descriptives
dd %>% dplyr::select(subj:vpsex, neo_n:neo_c) %>% psych::describe()
##       vars   n  mean    sd median trimmed   mad   min    max  range  skew
## subj     1 160 80.50 46.33  80.50   80.50 59.30  1.00 160.00 159.00  0.00
## vpage    2 160 22.98  4.09  22.00   22.24  1.48 18.00  46.00  28.00  2.95
## vpsex    3 160  0.50  0.50   0.50    0.50  0.74  0.00   1.00   1.00  0.00
## neo_n    4 160 -0.28  0.70  -0.33   -0.30  0.74 -1.83   1.75   3.58  0.28
## neo_e    5 160  0.49  0.48   0.50    0.49  0.37 -1.08   1.58   2.67 -0.18
## neo_o    6 160  0.68  0.54   0.75    0.71  0.56 -0.83   1.83   2.67 -0.39
## neo_a    7 160  0.62  0.49   0.67    0.63  0.49 -0.58   1.83   2.42 -0.16
## neo_c    8 160  0.65  0.61   0.75    0.67  0.62 -1.08   1.92   3.00 -0.33
##       kurtosis   se
## subj     -1.22 3.66
## vpage    11.57 0.32
## vpsex    -2.01 0.04
## neo_n    -0.31 0.06
## neo_e     0.28 0.04
## neo_o    -0.31 0.04
## neo_a    -0.29 0.04
## neo_c    -0.32 0.05
dd %>% dplyr::select(subj:vpsex, neo_n:neo_c) %>% psych::describeBy(dd$vpsex)
## 
##  Descriptive statistics by group 
## group: 0
##       vars  n  mean    sd median trimmed   mad   min    max  range  skew
## subj     1 80 80.10 47.15  78.50   80.27 59.30  1.00 160.00 159.00 -0.02
## vpage    2 80 22.69  4.54  21.00   21.88  1.48 18.00  46.00  28.00  3.32
## vpsex    3 80  0.00  0.00   0.00    0.00  0.00  0.00   0.00   0.00   NaN
## neo_n    4 80 -0.17  0.68  -0.17   -0.19  0.68 -1.50   1.33   2.83  0.22
## neo_e    5 80  0.52  0.48   0.58    0.52  0.37 -0.92   1.58   2.50 -0.22
## neo_o    6 80  0.70  0.54   0.75    0.73  0.62 -0.67   1.83   2.50 -0.31
## neo_a    7 80  0.82  0.47   0.83    0.84  0.49 -0.25   1.83   2.08 -0.34
## neo_c    8 80  0.77  0.56   0.83    0.79  0.49 -0.50   1.92   2.42 -0.36
##       kurtosis   se
## subj     -1.22 5.27
## vpage    13.48 0.51
## vpsex      NaN 0.00
## neo_n    -0.61 0.08
## neo_e     0.29 0.05
## neo_o    -0.41 0.06
## neo_a    -0.26 0.05
## neo_c    -0.41 0.06
## ------------------------------------------------------------ 
## group: 1
##       vars  n  mean    sd median trimmed   mad   min    max  range  skew
## subj     1 80 80.90 45.80  83.50   80.67 60.05  2.00 159.00 157.00  0.03
## vpage    2 80 23.26  3.61  22.00   22.61  1.48 19.00  39.00  20.00  2.18
## vpsex    3 80  1.00  0.00   1.00    1.00  0.00  1.00   1.00   0.00   NaN
## neo_n    4 80 -0.39  0.71  -0.42   -0.42  0.68 -1.83   1.75   3.58  0.38
## neo_e    5 80  0.46  0.48   0.50    0.45  0.49 -1.08   1.58   2.67 -0.14
## neo_o    6 80  0.66  0.53   0.75    0.69  0.49 -0.83   1.67   2.50 -0.46
## neo_a    7 80  0.41  0.42   0.42    0.43  0.37 -0.58   1.25   1.83 -0.33
## neo_c    8 80  0.53  0.64   0.54    0.54  0.56 -1.08   1.83   2.92 -0.20
##       kurtosis   se
## subj     -1.28 5.12
## vpage     5.50 0.40
## vpsex      NaN 0.00
## neo_n    -0.03 0.08
## neo_e     0.22 0.05
## neo_o    -0.29 0.06
## neo_a    -0.32 0.05
## neo_c    -0.39 0.07
# rescaling of the cluster variables...
dd.t <- dd %>% dplyr::select(neo_n:neo_c) %>% scale() %>% data.frame
colnames(dd.t) <- c("neo_n_z","neo_e_z", "neo_o_z", "neo_a_z", "neo_c_z")
dd <- cbind(dd, dd.t)

# the distances
dd.s <- dd %>% dplyr::filter(vpsex == 1, vpage > 22) %>%  dplyr::select(neo_n_z:neo_c_z)
dists <- dd.s %>% dist()
dists[1:6]
## [1] 2.53 4.10 3.23 1.70 2.13 2.90
#cutree(hclust(dists,method="single"),h=3.8)

# some linkage variants as proposed by Everitt
plot(hclust(dists, method="single"),  ylab="Height", sub="Single linkage")

plot(hclust(dists, method="complete"),ylab="Height", sub="Complete linkage")

plot(hclust(dists, method="average"), ylab="Height", sub="Average linkage")

# k-means
#there are random starts involved so we set a seed
set.seed(1234)
#running a cluster analysis

# we set 3 Clusters and use the scores
model <- dd %>% dplyr::select(neo_n_z:neo_c_z) %>% kmeans(centers=3, iter.max=1000, nstart=1000)
model
## K-means clustering with 3 clusters of sizes 47, 62, 51
## 
## Cluster means:
##   neo_n_z neo_e_z neo_o_z neo_a_z neo_c_z
## 1  -0.717   0.604   0.588   0.580   0.355
## 2   0.647  -0.550   0.467  -0.609  -0.491
## 3  -0.126   0.112  -1.110   0.206   0.270
## 
## Clustering vector:
##   [1] 1 1 2 1 1 3 2 1 2 2 1 2 1 1 2 1 1 2 3 3 3 2 3 1 3 1 2 3 3 1 3 3 3 2 2 1 1
##  [38] 2 3 1 3 2 2 2 2 3 3 3 2 2 2 1 2 3 2 3 1 2 3 3 2 3 2 3 2 2 3 3 3 1 2 2 2 2
##  [75] 2 1 1 2 1 2 2 2 3 2 3 2 2 1 2 3 2 1 3 1 3 3 2 1 3 1 3 3 3 3 1 1 2 1 3 1 1
## [112] 1 3 2 2 2 1 3 1 1 1 1 2 2 2 3 2 1 2 1 2 2 3 2 1 2 1 1 3 2 2 1 3 3 3 1 3 2
## [149] 2 3 2 2 3 2 3 1 3 2 1 3
## 
## Within cluster sum of squares by cluster:
## [1] 145 248 156
##  (between_SS / total_SS =  30.9 %)
## 
## Available components:
## 
## [1] "cluster"      "centers"      "totss"        "withinss"     "tot.withinss"
## [6] "betweenss"    "size"         "iter"         "ifault"
# if we want to use the clusters furtheron f. e. for some analyses, we store the cluster assignment
dd$cluster <- model$cluster


# we visualize the clusters
# we store the above calculated unstandardized means
m_z <- dd %>% dplyr::group_by(cluster) %>% dplyr::select(neo_n_z:neo_c_z) %>% dplyr::summarize_all(mean)
## Adding missing grouping variables: `cluster`
m_u <- dd %>% dplyr::group_by(cluster) %>% dplyr::select(neo_n:neo_c) %>% dplyr::summarize_all(mean)
## Adding missing grouping variables: `cluster`
dd %>% ggplot(aes(x=neo_n,y=neo_e)) +
  geom_point(color=model$cluster, alpha=.6) +#plotting alll the points
  #plotting the centroids
  geom_point(aes(x=as.numeric(m_u[1,"neo_n"]),y=as.numeric(m_u[1,"neo_e"])),color=1,size=5,shape=18) +
  geom_point(aes(x=as.numeric(m_u[2,"neo_n"]),y=as.numeric(m_u[2,"neo_e"])),color=2,size=5,shape=18) +
  geom_point(aes(x=as.numeric(m_u[3,"neo_n"]),y=as.numeric(m_u[3,"neo_e"])),color=3,size=5,shape=18)

dd %>% ggplot(aes(x=neo_e,y=neo_o)) +
  geom_point(color=model$cluster, alpha=.6) +#plotting alll the points
  #plotting the centroids
  geom_point(aes(x=as.numeric(m_u[1,"neo_e"]),y=as.numeric(m_u[1,"neo_o"])),color=1,size=5,shape=18) +
  geom_point(aes(x=as.numeric(m_u[2,"neo_e"]),y=as.numeric(m_u[2,"neo_o"])),color=2,size=5,shape=18) +
  geom_point(aes(x=as.numeric(m_u[3,"neo_e"]),y=as.numeric(m_u[3,"neo_o"])),color=3,size=5,shape=18)

dd %>% ggplot(aes(x=neo_o,y=neo_a)) +
  geom_point(color=model$cluster, alpha=.6) +#plotting alll the points
  #plotting the centroids
  geom_point(aes(x=as.numeric(m_u[1,"neo_o"]),y=as.numeric(m_u[1,"neo_a"])),color=1,size=5,shape=18) +
  geom_point(aes(x=as.numeric(m_u[2,"neo_o"]),y=as.numeric(m_u[2,"neo_a"])),color=2,size=5,shape=18) +
  geom_point(aes(x=as.numeric(m_u[3,"neo_o"]),y=as.numeric(m_u[3,"neo_a"])),color=3,size=5,shape=18)

dd %>% ggplot(aes(x=neo_a,y=neo_c)) +
  geom_point(color=model$cluster, alpha=.6) +#plotting alll the points
  #plotting the centroids
  geom_point(aes(x=as.numeric(m_u[1,"neo_a"]),y=as.numeric(m_u[1,"neo_c"])),color=1,size=5,shape=18) +
  geom_point(aes(x=as.numeric(m_u[2,"neo_a"]),y=as.numeric(m_u[2,"neo_c"])),color=2,size=5,shape=18) +
  geom_point(aes(x=as.numeric(m_u[3,"neo_a"]),y=as.numeric(m_u[3,"neo_c"])),color=3,size=5,shape=18)

# we can also use mclust::clPairs() to get an grafical overview
dd %>% dplyr::select(neo_n:neo_c) %>% mclust::clPairs(dd$cluster)

# some graph to choose a suitable number of clusters
#making a empty dataframe
criteria <- data.frame()
#setting range of k                   
nk <- 1:10
#loop for range of clusters
for (k in nk) {
  # model <- kmeans(dailyscale[,c("lteq","posaff")], k)
  model <- dd %>% dplyr::select(neo_n:neo_c) %>% kmeans(centers=k, iter.max=1000, nstart=1000)
  criteria <- rbind(criteria,c(k,model$tot.withinss,model$betweenss,model$totss))
}
#renaming columns
names(criteria) <- c("k","tot.withinss","betweenss","totalss")

#scree plot
ggplot(criteria, aes(x=k)) +
  geom_point(aes(y=tot.withinss),color="red") +
  geom_line(aes(y=tot.withinss),color="red") +
  geom_point(aes(y=betweenss),color="blue") +
  geom_line(aes(y=betweenss),color="blue") +
  xlab("k = number of clusters") + ylab("Sum of Squares (within = red, between = blue)")

## Model Based Clustering

# source
# https://cran.r-project.org/web/packages/mclust/vignettes/mclust.html
library(mclust)

X <- dd %>% dplyr::select(neo_n_z:neo_c_z)
head(X)
##   neo_n_z neo_e_z neo_o_z neo_a_z neo_c_z
## 1   0.162   0.714  -0.182   0.613   0.437
## 2  -0.549   0.369   0.906  -1.090   0.847
## 3   0.517  -0.149   0.440  -1.601   0.573
## 4  -1.378   0.369   0.440   1.294   2.080
## 5  -0.549   0.196   1.061   1.635   0.984
## 6   0.162   1.231  -0.803   0.613   0.573
BIC <- mclust::mclustBIC(X)
plot(BIC)

summary(BIC)
## Best BIC values:
##          EII,1 VII,1    EII,2
## BIC      -2296 -2296 -2299.02
## BIC diff     0     0    -3.29
mod1 <- mclust::Mclust(X, x = BIC)
# summary(mod1, parameters = TRUE)

# `mclustBIC()` recommends 1 cluster, so the plot is not very informative ;-)
plot(mod1, what = "classification")

Example Medical Costs

source

Columns

  • age: age of primary beneficiary

  • sex: insurance contractor gender, female, male

  • bmi: Body mass index, providing an understanding of body, weights that are relatively high or low relative to height, objective index of body weight (kg / m ^ 2) using the ratio of height to weight, ideally 18.5 to 24.9

  • children: Number of children covered by health insurance / Number of dependents

  • smoker: Smoking

  • region: the beneficiary’s residential area in the US, northeast, southeast, southwest, northwest.

  • charges: Individual medical costs billed by health insurance

Download from github

require(tidyverse)
set.seed(1234)
# the data come from https://www.kaggle.com/mirichoi0218/insurance
# alternatively: https://github.com/stedy/Machine-Learning-with-R-datasets
# we read from a local server for conveniance
dd <- readr::read_csv("http://md.psych.bio.uni-goettingen.de/mv/data/div/insurance.csv")
## Rows: 1338 Columns: 7
## ── Column specification ────────────────────────────────────────────────────────
## Delimiter: ","
## chr (3): sex, smoker, region
## dbl (4): age, bmi, children, charges
## 
## ℹ Use `spec()` to retrieve the full column specification for this data.
## ℹ Specify the column types or set `show_col_types = FALSE` to quiet this message.
dd <- cbind(1:nrow(dd), dd)
names(dd)[1] <- "subj"
dd <- dd %>% dplyr::mutate(gender_f = ifelse(sex == "female", 1, 0)) %>% dplyr::mutate(smoker_t = ifelse(smoker == "yes", 1, 0))

# rescaling of the cluster variables...
dd.t <- dd %>% dplyr::select(age, gender_f, bmi, children, smoker_t, charges) %>% scale() %>% data.frame()
colnames(dd.t) <- c("age_z","gender_f_z", "bmi_z", "children_z", "smoker_t_z", "charges_z")
dd <- cbind(dd, dd.t)

# we add a categorial variable bmi_class
dd <- dd %>% dplyr::mutate(bmi_class = ifelse(bmi <= 18.5, 0, 
                                                ifelse(bmi >18.5 & bmi <= 25, 1,
                                                ifelse(bmi > 25 & bmi < 30, 2, 3))))
# we take a look at the data structure
head(dd)
##   subj age    sex  bmi children smoker    region charges gender_f smoker_t
## 1    1  19 female 27.9        0    yes southwest   16885        1        1
## 2    2  18   male 33.8        1     no southeast    1726        0        0
## 3    3  28   male 33.0        3     no southeast    4449        0        0
## 4    4  33   male 22.7        0     no northwest   21984        0        0
## 5    5  32   male 28.9        0     no northwest    3867        0        0
## 6    6  31 female 25.7        0     no southeast    3757        1        0
##    age_z gender_f_z  bmi_z children_z smoker_t_z charges_z bmi_class
## 1 -1.438      1.010 -0.453    -0.9083      1.970     0.298         2
## 2 -1.509     -0.989  0.509    -0.0787     -0.507    -0.953         3
## 3 -0.798     -0.989  0.383     1.5803     -0.507    -0.728         3
## 4 -0.442     -0.989 -1.305    -0.9083     -0.507     0.720         1
## 5 -0.513     -0.989 -0.292    -0.9083     -0.507    -0.777         2
## 6 -0.584      1.010 -0.807    -0.9083     -0.507    -0.786         2
# todo: descriptive plot

# the distances
# we reduce our observations
s.sel <- sample(dd$subj, 50)
dd.s <- dd[dd$subj %in% s.sel,]

dists <- dd.s %>% dplyr::select(age_z,gender_f_z, bmi_z, children_z, smoker_t_z, charges_z) %>% dist()
dists[1:6]
## [1] 3.87 3.15 2.93 2.90 2.84 2.53
# dists
# some linkage variants as proposed by Everitt
plot(hclust(dists, method="single"),  ylab="Height", sub="Single linkage")

plot(hclust(dists, method="complete"),ylab="Height", sub="Complete linkage")

plot(hclust(dists, method="average"), ylab="Height", sub="Average linkage")

# we create an elbow visualization, a graph to choose a suitable number of clusters
# making an empty dataframe
criteria <- data.frame()
#setting range of k                   
nk <- 1:10
#loop for range of clusters
for (k in nk) {
  #model <- dd %>% dplyr::select(age, sex.f, bmi, children, smoker.t, charges) %>% kmeans(centers=k, iter.max=1000, nstart=1000)
  model <- dd %>% dplyr::select(age_z,gender_f_z, bmi_z, children_z, smoker_t_z, charges_z) %>% kmeans(centers=k, iter.max=1000, nstart=1000)
  criteria <- rbind(criteria,c(k,model$tot.withinss,model$betweenss,model$totss))
}
#renaming columns
names(criteria) <- c("k","tot.withinss","betweenss","totalss")

#scree plot
ggplot(criteria, aes(x=k)) +
  geom_point(aes(y=tot.withinss),color="red") +
  geom_line(aes(y=tot.withinss),color="red") +
  geom_point(aes(y=betweenss),color="blue") +
  geom_line(aes(y=betweenss),color="blue") +
  xlab("k = number of clusters") + ylab("Sum of Squares (within = red, between = blue)")

# due to our visual impression, 5 (3, 4, 5) clusters might be a good selection 



# k-means 
#running a cluster analysis

# we set 3 Clusters and use the scores
n_clusters = 5
model <- dd %>% dplyr::select(age_z, gender_f_z, bmi_z, children_z, smoker_t_z, charges_z) %>% kmeans(centers=n_clusters, iter.max=1000, nstart=1000)
# model
attributes(model)
## $names
## [1] "cluster"      "centers"      "totss"        "withinss"     "tot.withinss"
## [6] "betweenss"    "size"         "iter"         "ifault"      
## 
## $class
## [1] "kmeans"
# if we want to use the clusters furtheron f. e. for some analyses, we store the cluster assignment
dd$kmc_5 <- factor(model$cluster)

# we store the above calculated unstandardized means
m_u <- dd %>% dplyr::group_by(kmc_5) %>% dplyr::select(age, gender_f, bmi, children, smoker_t, charges) %>% dplyr::summarize_all(mean)
## Adding missing grouping variables: `kmc_5`
# we visualize the clusters to check the effect of the clustering variables
library(scales)
## 
## Attache Paket: 'scales'
## 
## Die folgenden Objekte sind maskiert von 'package:psych':
## 
##     alpha, rescale
## 
## Das folgende Objekt ist maskiert 'package:purrr':
## 
##     discard
## 
## Das folgende Objekt ist maskiert 'package:readr':
## 
##     col_factor
# hue_pal()(n_clusters)
# show_col(hue_pal()(n_clusters))

dd %>% ggplot(aes(x=age,y=charges, color=kmc_5)) +
  geom_point(alpha=.6) +#plotting alll the points
  #plotting the centroids
  geom_point(aes(x=as.numeric(m_u[1,"age"]),y=as.numeric(m_u[1,"charges"])),color=hue_pal()(n_clusters)[1],size=5,shape=18) +
  geom_point(aes(x=as.numeric(m_u[2,"age"]),y=as.numeric(m_u[2,"charges"])),color=hue_pal()(n_clusters)[2],size=5,shape=18) +
  geom_point(aes(x=as.numeric(m_u[3,"age"]),y=as.numeric(m_u[3,"charges"])),color=hue_pal()(n_clusters)[3],size=5,shape=18) +
  geom_point(aes(x=as.numeric(m_u[4,"age"]),y=as.numeric(m_u[4,"charges"])),color=hue_pal()(n_clusters)[4],size=5,shape=18) +
  geom_point(aes(x=as.numeric(m_u[5,"age"]),y=as.numeric(m_u[5,"charges"])),color=hue_pal()(n_clusters)[5],size=5,shape=18)

dd %>% ggplot(aes(x=bmi,y=charges, color=kmc_5)) +
  geom_point(alpha=.6) +#plotting alll the points
  #plotting the centroids
  geom_point(aes(x=as.numeric(m_u[1,"bmi"]),y=as.numeric(m_u[1,"charges"])),color=hue_pal()(n_clusters)[1],size=5,shape=18) +
  geom_point(aes(x=as.numeric(m_u[2,"bmi"]),y=as.numeric(m_u[2,"charges"])),color=hue_pal()(n_clusters)[2],size=5,shape=18) +
  geom_point(aes(x=as.numeric(m_u[3,"bmi"]),y=as.numeric(m_u[3,"charges"])),color=hue_pal()(n_clusters)[3],size=5,shape=18) +
  geom_point(aes(x=as.numeric(m_u[4,"bmi"]),y=as.numeric(m_u[4,"charges"])),color=hue_pal()(n_clusters)[4],size=5,shape=18) +
  geom_point(aes(x=as.numeric(m_u[5,"bmi"]),y=as.numeric(m_u[5,"charges"])),color=hue_pal()(n_clusters)[5],size=5,shape=18)

dd %>% ggplot(aes(x=children,y=charges, color=kmc_5)) +
  # geom_point(alpha=.6) +#plotting alll the points
  geom_jitter(alpha=.6, width=0.2) +#plotting alll the points
  #plotting the centroids
  geom_point(aes(x=as.numeric(m_u[1,"children"]),y=as.numeric(m_u[1,"charges"])),color=hue_pal()(n_clusters)[1],size=5,shape=18) +
  geom_point(aes(x=as.numeric(m_u[2,"children"]),y=as.numeric(m_u[2,"charges"])),color=hue_pal()(n_clusters)[2],size=5,shape=18) +
  geom_point(aes(x=as.numeric(m_u[3,"children"]),y=as.numeric(m_u[3,"charges"])),color=hue_pal()(n_clusters)[3],size=5,shape=18) +
  geom_point(aes(x=as.numeric(m_u[4,"children"]),y=as.numeric(m_u[4,"charges"])),color=hue_pal()(n_clusters)[4],size=5,shape=18) +
  geom_point(aes(x=as.numeric(m_u[5,"children"]),y=as.numeric(m_u[5,"charges"])),color=hue_pal()(n_clusters)[5],size=5,shape=18)

# we check other variables in the cluster Space

## Model Based Clustering

# source
# https://cran.r-project.org/web/packages/mclust/vignettes/mclust.html
library(mclust)

# X <- dd %>% dplyr::select(age, sex.f, bmi, children, smoker.t, charges)
X <- dd %>% dplyr::select(age_z:charges_z)
head(X)
##    age_z gender_f_z  bmi_z children_z smoker_t_z charges_z
## 1 -1.438      1.010 -0.453    -0.9083      1.970     0.298
## 2 -1.509     -0.989  0.509    -0.0787     -0.507    -0.953
## 3 -0.798     -0.989  0.383     1.5803     -0.507    -0.728
## 4 -0.442     -0.989 -1.305    -0.9083     -0.507     0.720
## 5 -0.513     -0.989 -0.292    -0.9083     -0.507    -0.777
## 6 -0.584      1.010 -0.807    -0.9083     -0.507    -0.786
BIC <- mclust::mclustBIC(X)
plot(BIC)
summary(BIC)
## Best BIC values:
##           VII,9  VII,8  VII,7
## BIC      -19171 -19329 -19624
## BIC diff      0   -158   -453
mod1 <- mclust::Mclust(X, x = BIC)

# this output is long, just to show that it exists
# summary(mod1, parameters = TRUE)

plot(mod1, what = "BIC")

plot(mod1, what = "classification")

# we store the model based classification
dd$mbc_9 <- mod1$classification

# we might want to inspect the cluster means in original scale
(m_u <- dd %>% dplyr::group_by(mbc_9) %>% dplyr::select(age, gender_f, bmi, children, smoker_t, charges) %>% dplyr::summarize_all(mean) )
## Adding missing grouping variables: `mbc_9`
## # A tibble: 9 × 7
##   mbc_9   age gender_f   bmi children smoker_t charges
##   <dbl> <dbl>    <dbl> <dbl>    <dbl>    <dbl>   <dbl>
## 1     1  36.2    0.507  25.5    1.01     0.978  21892.
## 2     2  24.5    0      28.4    0.324    0       2844.
## 3     3  37.5    0      28.6    2.62     0       8626.
## 4     4  42.2    0.524  39.5    1.02     0      10264.
## 5     5  26.2    1      28.0    0.316    0       4105.
## 6     6  52.6    1      28.7    0.371    0      11651.
## 7     7  40.2    1      29.2    2.58     0       9648.
## 8     8  40.6    0.331  35.7    1.19     1      41938.
## 9     9  53.5    0      29.6    0.396    0      11392.
# ... our attention might be drawn to the two clusters that share the highest charges and smokers

# we can look at classification dependent tables
table(dd$gender_f, mod1$classification)
##    
##       1   2   3   4   5   6   7   8   9
##   0  68 142 143  91   0   0   0  93 139
##   1  70   0   0 100 155 140 151  46   0
# or 
table(dd$gender_f, dd$mbc_9)
##    
##       1   2   3   4   5   6   7   8   9
##   0  68 142 143  91   0   0   0  93 139
##   1  70   0   0 100 155 140 151  46   0
# we can also use mclust::clPairs() to plot other classifications
table(dd$kmc_5)
## 
##   1   2   3   4   5 
## 237 265 280 273 283
mclust::clPairs(X, dd$kmc_5)

table(dd$bmi_class)
## 
##   0   1   2   3 
##  21 226 384 707
mclust::clPairs(X, dd$bmi_class)

Example Mall Customers

You are owing a supermarket mall and through membership cards , you have some basic data about your customers like Customer ID, age, gender, annual income and spending score.

Spending Score is something you assign to the customer based on your defined parameters like customer behavior and purchasing data.

These are simulated data for learning purposes.

source

require(tidyverse)
library(scales)
# the data come from https://www.kaggle.com/mirichoi0218/insurance
# we read from a local server for conveniance
dd <- readr::read_csv("http://md.psych.bio.uni-goettingen.de/mv/data/div/mall_customers.csv")
## Rows: 200 Columns: 5
## ── Column specification ────────────────────────────────────────────────────────
## Delimiter: ","
## chr (1): Gender
## dbl (4): CustomerID, Age, Annual Income (k$), Spending Score (1-100)
## 
## ℹ Use `spec()` to retrieve the full column specification for this data.
## ℹ Specify the column types or set `show_col_types = FALSE` to quiet this message.
# we take a look at the data structure
colnames(dd) <- c("subj", "gender", "age", "income", "spending_score")
head(dd)
## # A tibble: 6 × 5
##    subj gender   age income spending_score
##   <dbl> <chr>  <dbl>  <dbl>          <dbl>
## 1     1 Male      19     15             39
## 2     2 Male      21     15             81
## 3     3 Female    20     16              6
## 4     4 Female    23     16             77
## 5     5 Female    31     17             40
## 6     6 Female    22     17             76
dd <- dd %>% dplyr::mutate(genderf = ifelse(gender == "Female", 1, 0)) 

# standardization
dd.z <- dd %>% dplyr::select(age, income, spending_score, genderf) %>% scale() %>% data.frame
colnames(dd.z) <- c("age_z", "income_z", "spending_score_z", "genderf_z")
dd <- cbind(dd, dd.z)
head(dd)
##   subj gender age income spending_score genderf  age_z income_z
## 1    1   Male  19     15             39       0 -1.421    -1.73
## 2    2   Male  21     15             81       0 -1.278    -1.73
## 3    3 Female  20     16              6       1 -1.349    -1.70
## 4    4 Female  23     16             77       1 -1.135    -1.70
## 5    5 Female  31     17             40       1 -0.562    -1.66
## 6    6 Female  22     17             76       1 -1.206    -1.66
##   spending_score_z genderf_z
## 1           -0.434    -1.125
## 2            1.193    -1.125
## 3           -1.712     0.884
## 4            1.038     0.884
## 5           -0.395     0.884
## 6            0.999     0.884
# we create an elbow visualization, a graph to choose a suitable number of clusters
criteria <- data.frame()
nk <- 1:10
#loop for range of clusters
for (k in nk) {
  model <- dd %>% dplyr::select(age_z:genderf_z) %>% kmeans(centers=k, iter.max=1000, nstart=1000)
  criteria <- rbind(criteria,c(k,model$tot.withinss,model$betweenss,model$totss))
}
#renaming columns
names(criteria) <- c("k","tot.withinss","betweenss","totalss")

#scree plot
ggplot(criteria, aes(x=k)) +
  geom_point(aes(y=tot.withinss),color="red") +
  geom_line(aes(y=tot.withinss),color="red") +
  geom_point(aes(y=betweenss),color="blue") +
  geom_line(aes(y=betweenss),color="blue") +
  xlab("k = number of clusters") + ylab("Sum of Squares (within = red, between = blue)")

# k-means 4 Clusters and use the scores
n_clusters = 4
model <- dd %>% dplyr::select(age_z:genderf_z) %>% kmeans(centers=n_clusters, iter.max=1000, nstart=1000)
model
## K-means clustering with 4 clusters of sizes 48, 57, 55, 40
## 
## Cluster means:
##    age_z income_z spending_score_z genderf_z
## 1  0.758   0.0707           -0.813    -1.125
## 2 -0.745  -0.0340            0.677     0.884
## 3  0.663  -0.0663           -0.597     0.884
## 4 -0.759   0.0548            0.832    -1.125
## 
## Clustering vector:
##   [1] 4 4 3 2 2 2 3 2 1 2 1 2 3 2 1 4 3 4 1 2 1 4 3 4 3 4 3 4 3 2 1 2 1 4 3 2 3
##  [38] 2 3 2 3 4 1 2 3 2 3 2 2 2 3 4 2 1 3 1 3 1 2 1 1 4 3 3 1 4 3 3 4 2 1 3 3 3
##  [75] 1 4 3 1 2 3 1 4 1 3 2 1 3 2 2 3 3 4 1 3 2 4 3 2 1 4 2 3 1 4 1 2 3 1 1 1 1
## [112] 2 3 4 2 2 3 3 3 3 4 3 2 4 2 2 1 4 1 4 1 4 2 2 1 2 3 4 1 2 3 4 2 2 1 4 1 2
## [149] 3 4 1 4 3 2 3 2 1 2 1 2 3 2 1 2 1 2 1 2 3 4 1 4 1 4 3 2 1 4 1 4 3 2 1 2 3
## [186] 4 3 4 3 2 3 2 1 2 3 2 3 4 1 4
## 
## Within cluster sum of squares by cluster:
## [1] 115.1  94.9 100.7  74.0
##  (between_SS / total_SS =  51.7 %)
## 
## Available components:
## 
## [1] "cluster"      "centers"      "totss"        "withinss"     "tot.withinss"
## [6] "betweenss"    "size"         "iter"         "ifault"
# if we want to use the clusters furtheron f. e. for some analyses, we store the cluster assignment
dd$kmc_4 <- factor(model$cluster)

# we store the unstandardized means of the cluster variables and take a look at it
( m_u <- dd %>% dplyr::group_by(kmc_4) %>% dplyr::select(age, income, spending_score, genderf) %>% dplyr::summarize_all(mean) )
## Adding missing grouping variables: `kmc_4`
## # A tibble: 4 × 5
##   kmc_4   age income spending_score genderf
##   <fct> <dbl>  <dbl>          <dbl>   <dbl>
## 1 1      49.4   62.4           29.2       0
## 2 2      28.4   59.7           67.7       1
## 3 3      48.1   58.8           34.8       1
## 4 4      28.2   62             71.7       0
dd %>% ggplot(aes(x=age,y=spending_score, color=kmc_4)) +
  geom_point(alpha=.6) +#plotting alll the points
  geom_point(aes(x=as.numeric(m_u[1,"age"]),y=as.numeric(m_u[1,"spending_score"])),color=hue_pal()(n_clusters)[1],size=5,shape=18) +
  geom_point(aes(x=as.numeric(m_u[2,"age"]),y=as.numeric(m_u[2,"spending_score"])),color=hue_pal()(n_clusters)[2],size=5,shape=18) +
  geom_point(aes(x=as.numeric(m_u[3,"age"]),y=as.numeric(m_u[3,"spending_score"])),color=hue_pal()(n_clusters)[3],size=5,shape=18) +
  geom_point(aes(x=as.numeric(m_u[4,"age"]),y=as.numeric(m_u[4,"spending_score"])),color=hue_pal()(n_clusters)[4],size=5,shape=18)

dd %>% ggplot(aes(x=income,y=spending_score, color=kmc_4)) +
  geom_point(alpha=.6) +#plotting alll the points
  geom_point(aes(x=as.numeric(m_u[1,"income"]),y=as.numeric(m_u[1,"spending_score"])),color=hue_pal()(n_clusters)[1],size=5,shape=18) +
  geom_point(aes(x=as.numeric(m_u[2,"income"]),y=as.numeric(m_u[2,"spending_score"])),color=hue_pal()(n_clusters)[2],size=5,shape=18) +
  geom_point(aes(x=as.numeric(m_u[3,"income"]),y=as.numeric(m_u[3,"spending_score"])),color=hue_pal()(n_clusters)[3],size=5,shape=18) +
  geom_point(aes(x=as.numeric(m_u[4,"income"]),y=as.numeric(m_u[4,"spending_score"])),color=hue_pal()(n_clusters)[4],size=5,shape=18)

## Model Based Clustering
library(mclust)
X <- dd %>% dplyr::select(age_z:genderf_z)
head(X)
##    age_z income_z spending_score_z genderf_z
## 1 -1.421    -1.73           -0.434    -1.125
## 2 -1.278    -1.73            1.193    -1.125
## 3 -1.349    -1.70           -1.712     0.884
## 4 -1.135    -1.70            1.038     0.884
## 5 -0.562    -1.66           -0.395     0.884
## 6 -1.206    -1.66            0.999     0.884
BIC <- mclust::mclustBIC(X)
plot(BIC)
summary(BIC)
## Best BIC values:
##          VII,9   VII,7   VII,8
## BIC      -2088 -2114.6 -2122.9
## BIC diff     0   -26.4   -34.7
mod1 <- mclust::Mclust(X, x = BIC)

# this output is long, just to show that it exists
# summary(mod1, parameters = TRUE)

plot(mod1, what = "BIC")

plot(mod1, what = "classification")

# we store the model based classification
dd$mbc_9 <- mod1$classification

# we might want to inspect the cluster means in original scale
(m_u <- dd %>% dplyr::group_by(mbc_9) %>% dplyr::select(age, income, spending_score, genderf) %>% dplyr::summarize_all(mean) )
## Adding missing grouping variables: `mbc_9`
## # A tibble: 9 × 5
##   mbc_9   age income spending_score genderf
##   <dbl> <dbl>  <dbl>          <dbl>   <dbl>
## 1     1  45.6   27.0           20.4   0.591
## 2     2  24.1   41.5           62.7   0    
## 3     3  25.5   25.7           80.5   1    
## 4     4  54.2   54.2           49.0   1    
## 5     5  27.5   56.9           46.7   1    
## 6     6  60     54.9           49.7   0    
## 7     7  33.6   81.6           83.2   0    
## 8     8  31.7   82.8           81.3   1    
## 9     9  40.4   90.7           25.1   0.425
# we can look at classification dependent tables
table(dd$genderf, dd$mbc_9)
##    
##      1  2  3  4  5  6  7  8  9
##   0  9 22  0  0  0 18 16  0 23
##   1 13  0 13 26 24  0  0 19 17

Segmentation Data

source

The dataset consists of information about the purchasing behavior of 2,000 individuals from a given area when entering a physical ‘FMCG’ store. All data has been collected through the loyalty cards they use at checkout. The data has been preprocessed and there are no missing values. In addition, the volume of the dataset has been restricted and anonymised to protect the privacy of the customers.

Variable Data type Range Description

  • ID numerical Integer Shows a unique identificator of a customer.

  • Sex categorical {0,1} Biological sex (gender) of a customer. In this dataset there are only 2 different options.

    • 0 male
  • 1 female

  • Marital status categorical {0,1} Marital status of a customer.

    • 0 single
    • 1 non-single (divorced / separated / married / widowed)
  • Age numerical Integer The age of the customer in years, calculated as current year minus the year of birth of the customer at the time of creation of the dataset

    • 18 Min value (the lowest age observed in the dataset)
    • 76 Max value (the highest age observed in the dataset)
  • Education categorical {0,1,2,3} Level of education of the customer

    • 0 other / unknown
    • 1 high school
    • 2 university
    • 3 graduate school
  • Income numerical Real Self-reported annual income in US dollars of the customer.

    • 35832 Min value (the lowest income observed in the dataset)
    • 309364 Max value (the highest income observed in the dataset)
  • Occupation categorical {0,1,2} Category of occupation of the customer.

    • 0 unemployed / unskilled
    • 1 skilled employee / official
    • 2 management / self-employed / highly qualified employee / officer
  • Settlement size categorical {0,1,2} The size of the city that the customer lives in.

    • 0 small city
    • 1 mid-sized city
    • 2 big city

Column names are changed in the example that follows

require(tidyverse)
library(scales)
set.seed(2341)
# the data come from https://www.kaggle.com/dev0914sharma/customer-clustering...
# we read from a local server for conveniance
dd <- readr::read_csv("https://md.psych.bio.uni-goettingen.de/mv/data/div/segmentation_data.csv")
## Rows: 2000 Columns: 8
## ── Column specification ────────────────────────────────────────────────────────
## Delimiter: ","
## dbl (8): ID, Sex, Marital status, Age, Education, Income, Occupation, Settle...
## 
## ℹ Use `spec()` to retrieve the full column specification for this data.
## ℹ Specify the column types or set `show_col_types = FALSE` to quiet this message.
colnames(dd) <- c("id", "genderf", "marital_status", "age", "education", "income", "occupation", "sett_size")
dd$id <- dd$id - 100000000
# we take a look at the data structure
head(dd)
## # A tibble: 6 × 8
##      id genderf marital_status   age education income occupation sett_size
##   <dbl>   <dbl>          <dbl> <dbl>     <dbl>  <dbl>      <dbl>     <dbl>
## 1     1       0              0    67         2 124670          1         2
## 2     2       1              1    22         1 150773          1         2
## 3     3       0              0    49         1  89210          0         0
## 4     4       0              0    45         1 171565          1         1
## 5     5       0              0    53         1 149031          1         1
## 6     6       0              0    35         1 144848          0         0
# we create a standardized version of our data
# dd.z <- dd %>% dplyr::select(genderf:sett_size)
# dd.z <- data.frame(scale(dd.z))
##dd.z <- dd %>% dplyr::select(genderf:sett_size) %>% scale() %>% data.frame
##dd.z <- cbind(dd$id, dd.z)
##names(dd.z)[1] <- "id"
##head(dd.z)

dd.t <- dd %>% dplyr::select(genderf:sett_size) %>% scale() %>% data.frame()
colnames(dd.t) <- c("genderf_z", "marital_status_z", "age_z", "education_z", "income_z", "occupation_z", "sett_size_z")
dd <- cbind(dd, dd.t)
# we take a look at the data structure
head(dd)
##   id genderf marital_status age education income occupation sett_size genderf_z
## 1  1       0              0  67         2 124670          1         2    -0.917
## 2  2       1              1  22         1 150773          1         2     1.090
## 3  3       0              0  49         1  89210          0         0    -0.917
## 4  4       0              0  45         1 171565          1         1    -0.917
## 5  5       0              0  53         1 149031          1         1    -0.917
## 6  6       0              0  35         1 144848          0         0    -0.917
##   marital_status_z   age_z education_z income_z occupation_z sett_size_z
## 1           -0.993  2.6530      1.6039   0.0975        0.297       1.552
## 2            1.007 -1.1868     -0.0634   0.7825        0.297       1.552
## 3           -0.993  1.1170     -0.0634  -0.8330       -1.269      -0.910
## 4           -0.993  0.7757     -0.0634   1.3281        0.297       0.321
## 5           -0.993  1.4584     -0.0634   0.7367        0.297       0.321
## 6           -0.993 -0.0776     -0.0634   0.6270       -1.269      -0.910
s.sel <- sample(dd$id, 50)
# dd.s  <- dd[dd$id %in% s.sel,] %>% dplyr::select(genderf:sett_size) 
dd.s  <- dd[dd$id %in% s.sel,] 
#dists <- dd.s %>% dist()
dists  <- dd[dd$id %in% s.sel,] %>% dplyr::select(genderf:sett_size) %>% dist()
dists[1:6]
## [1] 46868 61419 25071 47075  9048 33606
# dists
#cutree(hclust(dists,method="single"),h=3.8)

#dd.s.z  <- dd.z[dd.z$id %in% s.sel,] %>% dplyr::select(genderf:sett_size)
#dists.z <- dd.s.z %>% dist()
dists.z  <- dd[dd$id %in% s.sel,] %>% dplyr::select(genderf_z:sett_size_z) %>% dist()
dists.z[1:6]
## [1] 2.55 3.42 2.13 3.16 3.53 1.52
# we can get cluster membership for our observations for a specific method at a specific height
cutree(hclust(dists,method="complete"),h=40000)
##   21   26   52   85  127  148  150  235  239  339  364  369  428  431  473  513 
##    1    2    3    4    2    1    5    2    4    1    4    1    5    1    2    1 
##  532  563  591  604  629  662  731  821  923  934 1012 1090 1102 1151 1155 1158 
##    5    1    4    5    5    4    5    4    4    1    3    3    4    5    5    3 
## 1178 1215 1328 1365 1399 1407 1411 1504 1511 1557 1638 1666 1705 1742 1833 1862 
##    1    5    2    2    1    2    4    2    5    1    1    1    4    4    1    4 
## 1892 1933 
##    4    1
# and store it
dd.s$cu_h_40000 <- cutree(hclust(dists,method="complete"),h=40000)
# we can also store membership for a certain number of clusters
dd.s$cu_n_4 <- cutree(hclust(dists,method="complete"),k=4)
head(dd.s)
##      id genderf marital_status age education income occupation sett_size
## 21   21       0              0  48         1 118777          1         1
## 26   26       0              0  36         1  71909          0         0
## 52   52       0              0  30         0 180196          2         2
## 85   85       0              0  52         1  93706          0         0
## 127 127       0              1  40         1  71702          0         0
## 148 148       1              1  51         2 127825          1         0
##     genderf_z marital_status_z    age_z education_z income_z occupation_z
## 21     -0.917           -0.993  1.03171     -0.0634  -0.0571        0.297
## 26     -0.917           -0.993  0.00776     -0.0634  -1.2870       -1.269
## 52     -0.917           -0.993 -0.50421     -1.7306   1.5545        1.863
## 85     -0.917           -0.993  1.37302     -0.0634  -0.7150       -1.269
## 127    -0.917            1.007  0.34908     -0.0634  -1.2924       -1.269
## 148     1.090            1.007  1.28769      1.6039   0.1803        0.297
##     sett_size_z cu_h_40000 cu_n_4
## 21        0.321          1      1
## 26       -0.910          2      2
## 52        1.552          3      3
## 85       -0.910          4      1
## 127      -0.910          2      2
## 148      -0.910          1      1
# we can do the same with standardized cluster variables
dd.s$cz_h_5 <- cutree(hclust(dists.z,method="complete"),h=5)
# we can also store membership for a certain number of clusters
dd.s$cz_n_4 <- cutree(hclust(dists.z,method="complete"),k=4)
head(dd.s)
##      id genderf marital_status age education income occupation sett_size
## 21   21       0              0  48         1 118777          1         1
## 26   26       0              0  36         1  71909          0         0
## 52   52       0              0  30         0 180196          2         2
## 85   85       0              0  52         1  93706          0         0
## 127 127       0              1  40         1  71702          0         0
## 148 148       1              1  51         2 127825          1         0
##     genderf_z marital_status_z    age_z education_z income_z occupation_z
## 21     -0.917           -0.993  1.03171     -0.0634  -0.0571        0.297
## 26     -0.917           -0.993  0.00776     -0.0634  -1.2870       -1.269
## 52     -0.917           -0.993 -0.50421     -1.7306   1.5545        1.863
## 85     -0.917           -0.993  1.37302     -0.0634  -0.7150       -1.269
## 127    -0.917            1.007  0.34908     -0.0634  -1.2924       -1.269
## 148     1.090            1.007  1.28769      1.6039   0.1803        0.297
##     sett_size_z cu_h_40000 cu_n_4 cz_h_5 cz_n_4
## 21        0.321          1      1      1      1
## 26       -0.910          2      2      2      2
## 52        1.552          3      3      1      1
## 85       -0.910          4      1      2      2
## 127      -0.910          2      2      2      2
## 148      -0.910          1      1      3      3
# some linkage variants as proposed by Everitt
plot(hclust(dists, method="single"),  ylab="Height", sub="Single linkage")

plot(hclust(dists, method="complete"),ylab="Height", sub="Complete linkage")

plot(hclust(dists, method="average"), ylab="Height", sub="Average linkage")

# we compare the dentrograms, both of type Complete Linkage
plot(hclust(dists, method="complete"),ylab="Height", sub="Complete linkage")

plot(hclust(dists.z, method="complete"),ylab="Height", sub="Complete linkage")

# we keep on with standardized cluster variables and create an elbow visualization, 
# ... a graph to choose a suitable number of clusters
criteria <- data.frame()
nk <- 1:10
#loop for range of clusters
for (k in nk) {
  model <- dd %>% dplyr::select(genderf_z:sett_size_z) %>% kmeans(centers=k, iter.max=1000, nstart=1000)
  criteria <- rbind(criteria,c(k,model$tot.withinss,model$betweenss,model$totss))
}
#renaming columns
names(criteria) <- c("k","tot.withinss","betweenss","totalss")

#scree plot
ggplot(criteria, aes(x=k)) +
  geom_point(aes(y=tot.withinss),color="red") +
  geom_line(aes(y=tot.withinss),color="red") +
  geom_point(aes(y=betweenss),color="blue") +
  geom_line(aes(y=betweenss),color="blue") +
  xlab("k = number of clusters") + ylab("Sum of Squares (within = red, between = blue)")

# we might vote for 4 or 5 clusters

# k-means 4 Clusters and use the scores
n_clusters = 4
model <- dd %>% dplyr::select(genderf_z:sett_size_z) %>% kmeans(centers=n_clusters, iter.max=1000, nstart=1000)
model
## K-means clustering with 4 clusters of sizes 263, 570, 462, 705
## 
## Cluster means:
##   genderf_z marital_status_z   age_z education_z income_z occupation_z
## 1    0.0901            0.391  1.6890      1.8195    0.981        0.499
## 2   -0.8573           -0.645 -0.0234     -0.5080    0.532        0.723
## 3   -0.2091           -0.954 -0.0283     -0.4856   -0.606       -0.754
## 4    0.7966            1.001 -0.5927      0.0502   -0.399       -0.276
##   sett_size_z
## 1       0.457
## 2       0.965
## 3      -0.856
## 4      -0.389
## 
## Clustering vector:
##    [1] 1 4 3 2 2 3 2 2 1 2 4 4 4 3 4 4 3 2 1 2 2 2 3 2 2 3 3 1 2 1 2 2 2 3 4 3 2
##   [38] 2 2 2 2 4 3 2 1 4 3 4 3 4 3 2 2 3 1 3 2 4 4 4 2 2 1 2 4 2 4 4 2 4 4 3 2 4
##   [75] 2 1 2 2 3 4 1 2 4 1 3 4 4 2 2 2 2 2 4 2 2 1 1 2 2 2 3 3 4 2 4 2 2 2 4 4 2
##  [112] 4 2 4 2 2 4 4 4 2 4 1 3 1 4 2 3 2 2 4 4 2 3 2 4 4 2 1 2 4 4 4 2 2 4 2 4 1
##  [149] 2 2 3 2 2 2 2 4 2 4 2 3 2 4 2 1 2 2 4 4 4 2 3 4 2 3 2 1 1 2 2 1 2 2 3 2 2
##  [186] 2 1 3 4 4 2 3 2 4 2 2 4 4 2 2 3 4 2 4 3 2 3 2 4 2 2 4 2 1 3 4 2 2 4 1 4 4
##  [223] 2 2 2 2 2 2 2 2 2 3 3 4 3 2 2 1 4 2 4 2 2 4 4 2 2 3 2 4 4 4 4 2 2 3 3 2 4
##  [260] 1 2 1 2 1 3 3 3 4 1 2 2 4 2 2 4 2 4 4 4 2 2 2 3 1 2 4 2 2 1 1 4 2 1 2 1 4
##  [297] 4 3 2 2 4 1 3 3 2 2 4 4 4 4 3 3 4 4 3 2 3 4 2 4 2 4 2 3 4 3 2 4 2 2 1 4 2
##  [334] 4 2 1 4 4 2 4 4 4 2 2 3 4 2 4 3 2 4 4 2 2 2 3 2 2 4 4 1 2 4 2 3 3 2 4 2 1
##  [371] 2 2 4 1 1 4 4 2 1 4 2 1 4 2 3 4 4 2 2 4 2 4 2 4 2 2 1 1 1 4 2 4 2 3 3 4 2
##  [408] 2 2 2 4 2 2 3 4 2 3 4 4 4 4 2 3 2 4 2 3 2 2 4 1 2 2 4 2 4 4 4 3 4 2 4 2 3
##  [445] 2 4 4 3 1 1 2 4 2 2 2 2 2 3 4 2 2 2 4 2 2 1 4 2 4 3 4 4 3 2 4 4 3 2 3 2 4
##  [482] 3 1 4 2 2 2 1 3 2 2 1 4 3 3 2 2 3 4 4 4 2 1 3 4 3 2 2 2 2 2 2 2 4 3 4 3 4
##  [519] 2 2 2 4 2 4 4 2 4 3 4 3 3 4 4 4 2 2 1 4 2 4 4 1 3 3 3 2 4 2 4 2 4 3 4 2 1
##  [556] 3 4 4 3 3 2 3 4 2 2 4 4 2 3 4 4 3 4 4 3 4 4 4 4 4 2 3 4 3 1 4 3 3 4 1 1 1
##  [593] 4 4 2 4 4 3 3 2 1 4 4 2 4 2 1 1 2 3 4 4 4 4 4 2 2 3 4 4 2 2 2 4 1 2 2 2 2
##  [630] 1 4 2 2 4 4 3 4 2 4 3 4 3 2 4 2 2 2 4 2 3 2 3 2 2 3 2 3 2 4 2 4 4 2 2 4 2
##  [667] 2 4 3 3 3 2 2 2 3 4 2 4 1 4 1 2 2 1 3 2 2 2 2 2 2 4 2 3 2 3 3 4 2 2 4 2 1
##  [704] 2 4 4 2 4 4 3 2 4 2 3 2 1 2 2 2 2 2 4 4 1 4 4 1 4 1 2 2 3 4 4 4 4 2 3 2 4
##  [741] 2 3 2 2 2 3 4 4 3 2 1 4 4 4 2 4 1 2 3 2 1 4 3 2 2 3 4 4 2 3 4 2 2 2 1 4 2
##  [778] 4 2 1 2 1 3 4 1 3 3 2 2 2 1 2 4 1 2 4 2 4 1 3 2 4 4 3 4 2 4 1 2 4 2 4 2 2
##  [815] 2 1 1 4 1 2 4 2 3 3 2 4 4 2 2 2 2 4 2 1 4 2 4 4 1 1 3 3 4 3 2 3 1 4 1 3 2
##  [852] 3 3 3 2 2 1 3 4 2 2 4 4 3 3 4 4 2 2 4 1 2 2 4 2 1 2 2 2 3 2 1 2 1 1 1 2 2
##  [889] 2 2 2 2 3 2 2 2 4 4 4 2 2 1 2 2 2 2 3 4 4 4 4 4 4 2 3 1 3 1 2 2 4 2 4 2 1
##  [926] 2 4 2 1 3 3 4 2 2 4 2 4 2 2 2 2 3 2 3 1 4 2 2 4 2 3 2 4 2 4 1 3 3 3 2 4 1
##  [963] 2 3 4 4 3 1 2 3 2 3 4 2 4 1 1 2 3 2 2 2 2 2 3 4 2 1 2 3 3 3 4 2 2 4 2 2 3
## [1000] 2 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
## [1037] 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
## [1074] 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 1 2 4 2
## [1111] 1 2 2 2 2 2 2 2 2 2 2 1 2 2 2 2 2 1 2 2 2 3 2 2 2 2 2 2 1 2 2 2 1 1 2 2 2
## [1148] 1 4 2 2 2 2 2 1 2 2 2 2 2 4 2 2 2 4 2 2 2 1 2 2 2 3 1 2 2 2 2 2 3 3 2 2 4
## [1185] 2 1 2 3 2 3 2 2 2 3 2 3 2 2 2 2 2 2 2 2 2 2 2 2 3 2 2 2 4 2 2 2 2 2 2 2 2
## [1222] 2 2 2 2 2 2 2 2 2 4 2 2 2 2 2 2 1 2 1 2 2 4 2 2 2 3 3 2 2 2 2 2 4 2 2 2 3
## [1259] 4 2 2 4 2 2 1 2 2 2 4 2 2 2 2 2 2 2 1 1 2 2 3 2 2 2 2 1 2 4 2 2 2 2 2 2 3
## [1296] 2 2 1 2 2 3 1 4 3 1 4 4 4 4 4 4 4 3 4 4 4 1 4 4 3 4 3 4 4 4 4 4 4 3 3 1 1
## [1333] 4 4 4 4 4 3 4 4 4 4 4 4 4 4 4 3 4 3 3 4 4 1 4 4 3 4 4 1 4 4 4 4 3 4 2 4 3
## [1370] 3 4 4 4 4 4 4 4 3 4 3 4 3 4 4 4 3 4 3 4 4 4 1 4 1 4 4 3 1 4 4 4 4 3 4 4 4
## [1407] 3 4 4 3 1 3 4 1 4 2 4 3 4 4 4 4 4 4 4 4 2 4 1 4 1 4 1 3 4 3 4 4 4 4 4 4 4
## [1444] 4 4 3 4 3 3 3 4 2 4 4 4 4 1 4 4 3 4 4 4 4 4 4 4 1 3 1 4 1 4 3 4 4 4 1 4 3
## [1481] 1 4 3 1 4 4 3 4 4 4 4 3 4 4 3 1 4 4 3 4 3 4 3 4 4 4 4 3 3 1 1 3 4 4 4 3 3
## [1518] 4 4 4 4 4 4 4 4 4 3 4 3 3 4 4 1 4 4 3 4 4 1 4 4 4 4 3 4 2 4 3 3 4 4 4 4 4
## [1555] 4 4 3 4 3 4 3 4 4 4 3 4 3 4 4 4 1 4 1 4 4 3 1 4 4 4 4 3 4 4 4 3 4 4 3 1 3
## [1592] 4 1 4 2 4 3 4 4 4 4 3 3 4 4 4 4 3 3 4 4 3 4 3 3 3 4 4 3 4 3 4 4 3 3 3 4 3
## [1629] 3 3 3 4 4 4 3 4 3 3 3 3 4 3 3 3 3 4 3 3 4 4 4 3 3 3 4 3 3 4 4 4 3 4 3 3 3
## [1666] 4 4 4 4 4 4 4 3 3 4 3 3 4 4 3 3 4 3 4 3 3 3 3 4 4 4 3 3 4 3 3 4 3 4 4 3 3
## [1703] 3 4 3 3 3 4 4 4 3 4 4 3 3 4 4 3 3 4 4 4 3 3 3 3 3 3 4 3 4 4 4 3 3 4 3 4 4
## [1740] 4 3 3 3 3 3 4 3 4 3 3 4 4 3 3 4 4 3 3 3 4 3 4 3 4 3 3 4 3 3 4 4 3 3 4 3 3
## [1777] 4 3 4 3 4 4 4 3 3 3 4 3 4 3 3 3 3 4 4 4 4 3 4 4 3 3 4 4 4 3 3 4 4 3 4 3 3
## [1814] 3 3 3 3 4 3 4 3 4 4 4 4 4 3 4 4 3 4 3 4 4 4 4 3 4 3 3 4 3 4 4 3 4 3 4 4 4
## [1851] 4 4 3 3 4 4 4 4 3 3 4 4 3 4 3 3 3 4 4 3 3 3 4 4 3 3 3 4 3 3 3 3 4 4 4 3 4
## [1888] 3 3 3 4 4 3 3 3 3 4 3 3 4 4 4 3 3 3 4 3 3 4 4 4 3 4 3 3 3 4 4 4 4 4 4 4 3
## [1925] 3 4 3 3 4 4 3 3 4 3 4 3 3 3 3 4 4 4 3 3 4 3 3 4 3 4 4 3 3 3 4 3 3 3 4 4 4
## [1962] 3 4 4 3 3 4 4 3 3 4 4 4 3 3 3 3 3 3 4 3 4 4 4 3 3 4 3 4 4 4 3 3 3 3 3 4 3
## [1999] 4 3
## 
## Within cluster sum of squares by cluster:
## [1] 1688 2021 1506 1952
##  (between_SS / total_SS =  48.8 %)
## 
## Available components:
## 
## [1] "cluster"      "centers"      "totss"        "withinss"     "tot.withinss"
## [6] "betweenss"    "size"         "iter"         "ifault"
# if we want to use the clusters furtheron f. e. for some analyses, we store the cluster assignment
dd$kmc_4 <- factor(model$cluster)

# we store the unstandardized means of the cluster variables and take a look at it
( m_u <- dd %>% dplyr::group_by(kmc_4) %>% dplyr::select(genderf, marital_status, age, education, income, occupation, sett_size) %>% dplyr::summarize_all(mean) )
## Adding missing grouping variables: `kmc_4`
## # A tibble: 4 × 8
##   kmc_4 genderf marital_status   age education  income occupation sett_size
##   <fct>   <dbl>          <dbl> <dbl>     <dbl>   <dbl>      <dbl>     <dbl>
## 1 1      0.502          0.692   55.7     2.13  158338.      1.13     1.11  
## 2 2      0.0298         0.174   35.6     0.733 141218.      1.27     1.52  
## 3 3      0.353          0.0195  35.6     0.747  97860.      0.329    0.0433
## 4 4      0.854          0.997   29.0     1.07  105759.      0.634    0.423
dd %>% ggplot(aes(x=age,y=income, color=kmc_4)) +
  geom_point(alpha=.6) +
  geom_point(aes(x=as.numeric(m_u[1,"age"]),y=as.numeric(m_u[1,"income"])),color=hue_pal()(n_clusters)[1],size=5,shape=18) +
  geom_point(aes(x=as.numeric(m_u[2,"age"]),y=as.numeric(m_u[2,"income"])),color=hue_pal()(n_clusters)[2],size=5,shape=18) +
  geom_point(aes(x=as.numeric(m_u[3,"age"]),y=as.numeric(m_u[3,"income"])),color=hue_pal()(n_clusters)[3],size=5,shape=18) +
  geom_point(aes(x=as.numeric(m_u[4,"age"]),y=as.numeric(m_u[4,"income"])),color=hue_pal()(n_clusters)[4],size=5,shape=18)

## Model Based Clustering

# source
# https://cran.r-project.org/web/packages/mclust/vignettes/mclust.html
library(mclust)

X <- dd %>% dplyr::select(age, education, income, occupation)
head(X)
##   age education income occupation
## 1  67         2 124670          1
## 2  22         1 150773          1
## 3  49         1  89210          0
## 4  45         1 171565          1
## 5  53         1 149031          1
## 6  35         1 144848          0
# or a standardized version of it
X.z <- X %>% scale(center=TRUE, scale=TRUE)
# or less verbose
X.z <- X %>% scale()
head(X.z)
##          age education  income occupation
## [1,]  2.6530    1.6039  0.0975      0.297
## [2,] -1.1868   -0.0634  0.7825      0.297
## [3,]  1.1170   -0.0634 -0.8330     -1.269
## [4,]  0.7757   -0.0634  1.3281      0.297
## [5,]  1.4584   -0.0634  0.7367      0.297
## [6,] -0.0776   -0.0634  0.6270     -1.269
# fully explorative
mod_e <- mclust::densityMclust(X.z)

plot(mod_e, what = "BIC")

# more specific
mod <- mclust::densityMclust(X.z, G=1:5, modelNames=c("EEV", "VEV"))

plot(mod, what = "BIC")

summary(mod)
## ------------------------------------------------------- 
## Density estimation via Gaussian finite mixture modeling 
## ------------------------------------------------------- 
## 
## Mclust VEV (ellipsoidal, equal shape) model with 3 components: 
## 
##  log-likelihood    n df    BIC    ICL
##           -6546 2000 38 -13380 -13435
dd$mclust_c <- mod$classification
table(dd$mclust_c)
## 
##   1   2   3 
## 654 782 564
# we visualize the clusters in contexts
mclust::clPairs(X.z, mod$classification)

Remark: This is the base for the sheet on cluster analysis

Modelnames finden sich in der Dokumentation mclust:

Details
The following models are available in package mclust:
univariate mixture
  "E" equal variance (one-dimensional)
  "V" variable/unqual variance (one-dimensional)
multivariate mixture
  "EII" spherical, equal volume
  "VII" spherical, unequal volume
  "EEI" diagonal, equal volume and shape
  "VEI" diagonal, varying volume, equal shape
  "EVI" diagonal, equal volume, varying shape
  "VVI" diagonal, varying volume and shape
  "EEE" ellipsoidal, equal volume, shape, and orientation
  "VEE" ellipsoidal, equal shape and orientation (*)
  "EVE" ellipsoidal, equal volume and orientation (*)
  "VVE" ellipsoidal, equal orientation (*)
  "EEV" ellipsoidal, equal volume and equal shape
  "VEV" ellipsoidal, equal shape
  "EVV" ellipsoidal, equal volume (*)
  "VVV" ellipsoidal, varying volume, shape, and orientation

Check

  • Idee, “interessante” Gruppeneinteilungen in den Clustervariablen zu finden und ggf. weiter zu verwenden. Beobachtungen (Vpn) clustern im Gegensatz zu FA (Variablen clustern).

  • Clustering braucht numerische Variablen

  • Gleiche Skalierung der Variablen hilft, ev. z-Transformation via scale()

  • Agglomerative Hierarchical Clustering explorativ, Visualisierung der Struktur, Wahl eines Cut-Off und damit Festlegung auf Clusterzahl Export von Clusterzugehörigkeiten auf bestimmtem Level oder für bestimmte Anzahl von Clustern

– K-Means Clustering Cluster-Zahl muss vorgegeben werden, Problem, diese Zahl zu finden Cluster-Zugehörigkeiten und diverse andere Infos zu Clustern werden generiert

– Modell geleitetes Clustern Modell bezieht sich auf zulässige Clusterformen bei der Suche library(mclust) viele Utilities, z. B. Plot über Clustervariablen hinsichtlich einer Gruppierungsvariable via mclust::clPairs()

  • Zugriff auf Clusterzugehörigkeit der Beobachtungen cutree()

  • Interpretation der Clusterzentren charakterisiert die Beobachtungen in den Clustern. Die Clusterzentren sind die Mittelwerte der Variablen, über die die Cluster gebildet wurden, für das jeweilige Cluster. Wir suchen “charakteristische” Kombinationen von Variablenmittelwerten,

    1. B. “Personen mit hohem Einkommen, die verheiratet und über 60 Jahre alt sind”.

Example Medical Costs

Screencast

Clusteranalyse, Basics und ein Beispiel:

StudIP - ownCloud