Skip to content

Instantly share code, notes, and snippets.

@lundquist-ecology-lab
Last active January 25, 2023 01:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lundquist-ecology-lab/bec592869826fcaec573a02cd5fddb02 to your computer and use it in GitHub Desktop.
Save lundquist-ecology-lab/bec592869826fcaec573a02cd5fddb02 to your computer and use it in GitHub Desktop.
SImple PCA in R using iris dataset
# 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