hclust() a base R function (along with cutree() and dist()).
MDS Scaling
The mds() function in smacof lets us estimate multiple types of MDS:
mds(distance, type="interval") - Metric MDS
mds(distance, type="ordinal") - Non-Metric MDS
In both cases the distance object needs to be a symmetric dissimilarity (distance) matrix. Larger values mean observations are more different from each other.
You select the number of dimensions using ndim=
Recreating a Map from Distances
R has an object UScitiesD that you can call at anytime which shows the distances between several cities.
# UScitiesD #Run this by itself to seelibrary(smacof)mds <-mds(UScitiesD, type ="interval")mds$stress # The stress
I use the basic plot() function to make a scree plot:
plot(x =1:5, y = out, ylab ="Stress", xlab ="Dimensions", type ="b")
Hierarchical Clustering
The hclust() function needs a distance object to work. Our UN_votes data already shows “distances” but isn’t a distance object so we use as.dist() to convert it.
hcl <-hclust(as.dist(UN_votes))plot(hcl) ## creates a dendrogram
Methods of Aggregation
You can change the method with the method= argument (“single”, “complete”, “average”)
hcl <-hclust(as.dist(UN_votes), method ="single")plot(hcl) ## creates a dendrogram
Creating Groupings
The cutree() function “cuts the tree” to make clusters. Set k= to set the number of groups you want.
groups <-cutree(hcl, k =4)groups[1:20]
AFG ALB DZA ARG AUS AUT BRB BLR BEL BEN BOL BWA BRA BGR BFA BDI CIV KHM CMR CAN
1 2 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 3 1 1
Correspondence Analysis
For correspondence analysis we use the ca() function, as a default it will estimate the largest possible number of dimensions.
The data here shows the number of a majors that graduated from colleges in Ohio in 2024.
mat <-read.csv( here::here("resources/network_data/colleges.csv"),row.names =1)mat <-as.matrix(mat)colnames(mat) <-gsub("\\.", " ", colnames(mat))library(ca)ca_out <-ca(mat)
Correspondence Analysis - Dimensions
If you call summary() on your ca() object then the top of it will show you how much variance each dimension captures.
If we want to extract the scales we use cacoord() which has a variety of options under type=. What we want is either "rowprincipal" or "colprincpal"
majors_principal <-cacoord(ca_out, type ="rowprincipal")ggplot(majors_principal$rows, aes(x = Dim1, y = Dim2)) +geom_point(size =5) +theme_minimal()
Correspondence Analysis - Plotting Both
It will return an object with both $rows and $columns. If this is row principals then the rows are in principal components and the columns are standard components.