Data
perform.A = c(63.3, 68.3, 86.7, 52.8, 75, 58, 69.5, 32.7, 60.9, 58.2)
contracts.A = c(24, 30, 33, 19, 30, 22, 28, 13, 17, 18)
perform.B = c(72.8, 88.2, 80.8, 71.3, 81.5, 47.6, 81, 81.4, 83, 76, 74.5)
contracts.B = c(25, 26, 29, 22, 41, 15, 40, 37, 39, 29, 26)
perform.C = c(82.3, 89.7, 81, 85.1, 74.1, 75.9, 74.7, 81.1, 76.4, 81.8)
contracts.C = c(38, 42, 48, 42, 40, 45, 33, 31, 47, 38)
sales = c(perform.A, perform.B, perform.C)
contracts = c(contracts.A , contracts.B , contracts.C)
group = c(rep(1, 10), rep(2, 11), rep(3, 10))
group = factor(group, levels = c(1,2,3), labels = c("Α", "Β", "Γ"))
pca.data.frame = data.frame(group, sales, contracts)
1. Principal Component Analysis
my.pca = prcomp(pca.data.frame[, c(2,3)], center = TRUE, scale. = FALSE)
2. Plot canonical discriminant functions
pr.comp.plot.data = as.data.frame(my.pca$x)
pr.comp.plot.data$PC1 = scale(pr.comp.plot.data$PC1)
pr.comp.plot.data$PC2 = scale(pr.comp.plot.data$PC2)
pr.comp.plot.data$group = pca.data.frame$group
pr.comp.plot.data.A = pr.comp.plot.data[pr.comp.plot.data$group == "Α", ]
pr.comp.plot.data.B = pr.comp.plot.data[pr.comp.plot.data$group == "Β", ]
pr.comp.plot.data.C = pr.comp.plot.data[pr.comp.plot.data$group == "Γ", ]
x.center = c(mean(pr.comp.plot.data.A$PC1), mean(pr.comp.plot.data.B$PC1), mean(pr.comp.plot.data.C$PC1))
y.center = c(mean(pr.comp.plot.data.A$PC2), mean(pr.comp.plot.data.B$PC2), mean(pr.comp.plot.data.C$PC2))
center.data = data.frame(x.center, y.center)
center.data$group = factor(c("Α", "Β", "Γ"))
library(ggfortify)
my.plot = ggplot(pr.comp.plot.data, aes(x=PC1, y=PC2, group=group)) +
geom_point(aes(shape=group, color=group), size = 3) +
geom_point(data=center.data, shape=15, aes(x=x.center, y=y.center), colour="dodgerblue4", size=6)
my.plot + labs(x = "Principal Component 1", y = "Principal Component 2", title = "Canonical Discriminant Functions") +
annotate("text", x=center.data$x[1], y=center.data$y[1] + 0.3, label= "A") +
annotate("text", x=center.data$x[2], y=center.data$y[2] + 0.3, label= "B") +
annotate("text", x=center.data$x[3], y=center.data$y[3] + 0.3, label= "Γ")
The above example is contained in the paragraph 5.7 of the book "Στατιστική ανάλυση με τη γλώσσα R" (in Greek, ISBN: 978-960-93-9445-1) published in Thessaloniki, 2017.
Performing pca with factoshiny: https://socio-imagination.blogspot.com/2020/05/fhusson.html
ReplyDelete