# Generating random triangle vertices
# 1st column represents X coordinates, 2nd column represents Y coordinates
xy <- matrix(rnorm(3 * 2), ncol = 2)
xy <- xy[order(xy[, 1]), ]
# Number of random points
set.seed(16)
num_points <- 1000
random_values <- runif(num_points) # Generate random points
# Calculate the perimeter of the triangle
# First, add the first point of xy at the end to close the triangle,
# i.e., the first side between the 1st and 2nd rows
# 3rd side between the second-to-last and last rows
xy2 <- rbind(xy, xy[1, ])
side_lengths <- numeric(3)
for (k in 1:3) {
side_lengths[k] <- sqrt((xy2[k + 1, 1] - xy2[k, 1])^2 + (xy2[k + 1, 2] - xy2[k, 2])^2)
}
perimeter <- sum(side_lengths)
# Normalize random points to the perimeter
random_values <- random_values * perimeter
# Calculate the location of each point in the X and Y matrix
X1 <- Y1 <- X2 <- Y2 <- X3 <- Y3 <- numeric(0)
for (k in 1:num_points) {
if (random_values[k] < side_lengths[1]) {
# lies on side 1
X1 <- c(X1, xy2[1, 1] + (xy2[2, 1] - xy2[1, 1]) * random_values[k] / side_lengths[1])
Y1 <- c(Y1, xy2[1, 2] + (xy2[2, 2] - xy2[1, 2]) * random_values[k] / side_lengths[1])
} else if (random_values[k] < side_lengths[1] + side_lengths[2]) {
# lies on side 2
X2 <- c(X2, xy2[2, 1] + (xy2[3, 1] - xy2[2, 1]) * (random_values[k] - side_lengths[1]) / side_lengths[2])
Y2 <- c(Y2, xy2[2, 2] + (xy2[3, 2] - xy2[2, 2]) * (random_values[k] - side_lengths[1]) / side_lengths[2])
} else {
# lies on side 3
X3 <- c(X3, xy2[3, 1] + (xy2[4, 1] - xy2[3, 1]) * (random_values[k] - side_lengths[1] - side_lengths[2]) / side_lengths[3])
Y3 <- c(Y3, xy2[3, 2] + (xy2[4, 2] - xy2[3, 2]) * (random_values[k] - side_lengths[1] - side_lengths[2]) / side_lengths[3])
}
}
# Add noise to the generated points
noise_range <- c(-0.01, 0.01)
X1 <- X1 + runif(length(X1), min = noise_range[1], max = noise_range[2])
Y1 <- Y1 + runif(length(Y1), min = noise_range[1], max = noise_range[2])
X2 <- X2 + runif(length(X2), min = noise_range[1], max = noise_range[2])
Y2 <- Y2 + runif(length(Y2), min = noise_range[1], max = noise_range[2])
X3 <- X3 + runif(length(X3), min = noise_range[1], max = noise_range[2])
Y3 <- Y3 + runif(length(Y3), min = noise_range[1], max = noise_range[2])
# Plot
plot(xy2[, 1], xy2[, 2], col = "black", lty = 1)
points(X1, Y1, col = "black")
points(X2, Y2, col = "black")
points(X3, Y3, col = "black")
# Create matrices for each set of points
data_matrix_1 <- cbind(X1, Y1)
data_matrix_2 <- cbind(X2, Y2)
data_matrix_3 <- cbind(X3, Y3)
# Combine matrices into a single matrix
triangle_matrix <- rbind(data_matrix_1, data_matrix_2, data_matrix_3)
This codes creates a random triangle shape out of randomly created data points.Then those points are saved as a matrix - triangle_matrix
# MDS on the data
dist.reg<-dist(triangle_matrix) # as a main input we need distance between units
mds1<-cmdscale(dist.reg, k=2)
summary(mds1)
## V1 V2
## Min. :-0.79091 Min. :-0.5010
## 1st Qu.:-0.35440 1st Qu.:-0.2181
## Median : 0.03694 Median : 0.0943
## Mean : 0.00000 Mean : 0.0000
## 3rd Qu.: 0.36690 3rd Qu.: 0.2159
## Max. : 0.70663 Max. : 0.3012
plot(mds1[,1], mds1[,2]) # retrieved data
points(triangle_matrix, col="red") # empirical data
title(main="Points retrived from distance (black) vs. original points (red)")
After performing Multi-Dimensional-Scaling on this matrix the triangle shape is still visible, but the scaled points are shifted from the original triangle
# let’s check the impact of distance metric on quality of MDS
plot(triangle_matrix[,1], triangle_matrix[,2], ylim=c(-2,2), xlim=c(-2,2))
dist.reg<-dist(triangle_matrix, method="euclidean")
mds1<-cmdscale(dist.reg, k=2)
points(mds1[,1], mds1[,2], col="red")
dist.reg<-dist(triangle_matrix, method="manhattan")
mds2<-cmdscale(dist.reg, k=2)
points(mds2[,1], mds2[,2], col="blue")
dist.reg<-dist(triangle_matrix, method="canberra")
mds3<-cmdscale(dist.reg, k=2)
points(mds3[,1], mds3[,2], col="green")
dist.reg<-dist(triangle_matrix, method="maximum")
mds4<-cmdscale(dist.reg, k=2)
points(mds4[,1], mds4[,2], col="yellow")
dist.reg<-dist(triangle_matrix, method="minkowski", p=0.7)
mds5<-cmdscale(dist.reg, k=2)
points(mds5[,1], mds5[,2], col="pink")
options(repos = c(CRAN = "https://cran.rstudio.com"))
install.packages("StatMatch")
## Instalowanie pakietu w 'C:/Users/kaszt/AppData/Local/R/win-library/4.3'
## (ponieważ 'lib' nie jest określony)
## pakiet 'StatMatch' został pomyślnie rozpakowany oraz sumy MD5 zostały sprawdzone
##
## Pobrane pakiety binarne są w
## C:\Users\kaszt\AppData\Local\Temp\Rtmp2bzcS5\downloaded_packages
library(StatMatch)
## Warning: pakiet 'StatMatch' został zbudowany w wersji R 4.3.2
## Ładowanie wymaganego pakietu: proxy
##
## Dołączanie pakietu: 'proxy'
## Następujące obiekty zostały zakryte z 'package:stats':
##
## as.dist, dist
## Następujący obiekt został zakryty z 'package:base':
##
## as.matrix
## Ładowanie wymaganego pakietu: survey
## Warning: pakiet 'survey' został zbudowany w wersji R 4.3.2
## Ładowanie wymaganego pakietu: grid
## Ładowanie wymaganego pakietu: Matrix
## Ładowanie wymaganego pakietu: survival
##
## Dołączanie pakietu: 'survey'
## Następujący obiekt został zakryty z 'package:graphics':
##
## dotchart
## Ładowanie wymaganego pakietu: lpSolve
## Ładowanie wymaganego pakietu: ggplot2
dist.gower<-gower.dist(triangle_matrix) # library(StatMatch)
mds6<-cmdscale(dist.gower, k=2)
points(mds6[,1], mds6[,2], col="darkmagenta")
legend("bottomleft", col=c("black", "red", "blue", "green", "yellow", "pink", "darkmagenta"), c("empirical points", "Euclidean", "manhattan", "canberra", "maximum", "Minkowski p=0.7", "Gower"), pch=21, bty="n")
We can see that in case of triangle the shapes in each methods are very different from those that occured when performing same operations on the circular shape. As expected Euclidean method remained shape of the triangle.
# let’s generate z value for points (z as value of dot)
z<-as.data.frame(rnorm(dim(triangle_matrix)[1], 10,3))
triangle_matrix<-cbind(triangle_matrix,z)
colnames(triangle_matrix)<-c("x","y","z")
plot(triangle_matrix[,1:2], cex=triangle_matrix$z/2, pch=".", ylim=c(-1.1, 1.1), xlim=c(-1.1, 1.1))
We added third dimension to the matrix
# MDS on the xyz data
dist.reg<-dist(triangle_matrix) # distance but for three variables (x,y,z)
mds1<-cmdscale(dist.reg, k=2)
summary(mds1)
## V1 V2
## Min. :-13.029550 Min. :-0.79028
## 1st Qu.: -2.035577 1st Qu.:-0.35574
## Median : -0.001855 Median : 0.03192
## Mean : 0.000000 Mean : 0.00000
## 3rd Qu.: 1.918312 3rd Qu.: 0.36855
## Max. : 10.411019 Max. : 0.71379
plot(mds1[,1], mds1[,2])
points(triangle_matrix[,1:2], col="red") # empirical data
ploting non retrieved data keep the shape, similarly to the case of circle
plot(mds1[,1], mds1[,2], ylim=c(-10, 10), xlim=c(-10, 10)) # retrieved data
points(triangle_matrix[,1:2], col="red") # empirical data
ploting retrieved data keep the shape, similarly to the case of circle