Last active
January 25, 2023 01:54
-
-
Save lundquist-ecology-lab/bec592869826fcaec573a02cd5fddb02 to your computer and use it in GitHub Desktop.
SImple PCA in R using iris dataset
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Running a principal components analysis (PCA) in R | |
# Load data | |
data(iris) | |
# Remove factors | |
data <- iris | |
# Scale data | |
data_scaled <- scale(data[-5]) | |
# Perform PCA | |
pca_results <- prcomp(data_scaled, scale = TRUE) | |
# View results | |
summary(pca_results) | |
# Create biplot | |
# library(devtools) | |
# install_github("vqv/ggbiplot") | |
library(ggbiplot) | |
g <- ggbiplot(pca_results, choices=c(1,2), obs.scale = 1, var.scale = 1, groups = iris$Species, ellipse = TRUE) | |
g <- g + geom_point(aes(color = iris$Species), size = 3) | |
g <- g + theme_classic() | |
g <- g + scale_color_discrete(name = 'Species', labels = c("I. setosa", "I. versicolor", "I. virginica")) | |
g <- g + theme(legend.direction = 'horizontal', legend.position = 'top') | |
print(g) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment