Skip to content

Instantly share code, notes, and snippets.

@dgrapov dgrapov/pca.R
Created Mar 24, 2018

Embed
What would you like to do?
basic principal components analysis and visualization in R
# Basic PCA example
# use www.createdatasol.com for
# an advanced user interface
#required packages for plotting
library(ggplot2)
library(ggrepel)
#load data
data<-read.csv('~/Sampledata.csv',
header = TRUE,stringsAsFactors = FALSE)
#split numeric and text
is_num<-!sapply(data,class) %in% c('character','factor')
#calculate principal components
pca<-prcomp(data[,is_num])
# get sample scores and
# add meta data for visualization
plot_data<-cbind(data[,!is_num],pca$x)
#plot scores
ggplot(plot_data, aes(x=PC1,y=PC2)) +
geom_point(aes(color=Label,size=Age),alpha=.75) +
geom_text_repel(aes(label=ID),size=1.5) +
theme_classic()
@dgrapov

This comment has been minimized.

Copy link
Owner Author

dgrapov commented Mar 24, 2018

image

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.