Skip to content

Instantly share code, notes, and snippets.

@FelipeSBarros
Last active February 8, 2017 19:26
Show Gist options
  • Save FelipeSBarros/e0cb1a8669b295da6430 to your computer and use it in GitHub Desktop.
Save FelipeSBarros/e0cb1a8669b295da6430 to your computer and use it in GitHub Desktop.
Small function to create PCA analysis and spatial eigenvariables
eigenvariables.fct <- function(vars, name, proportion = 0.95){
library("raster")
if (file.exists("./pca") == FALSE) dir.create("./pca")
#Running PCA:
# Counts not NA cels
non.na <- sum(!is.na(values(vars[[1]])))
# Sample the study area with n-non.na and creates an environmental table
sr <- sampleRandom(vars, non.na)
# faz o PCA dessa tabela padronizada
pca <- prcomp(scale(sr))
summary.pca <- summary(pca)
#Saving results:
capture.output(pca, file = sprintf('./pca/%s.pca.txt', name))
#saving summary
capture.output(summary.pca, file = sprintf('./pca/%s.summary.pca.txt', name))
#Plotting results
#GGPLOT
#####
#library(ggplot2)
# create data frame with scores
#scores <- as.data.frame(pca$x)
# plot of observations
#ggplot(data = scores, aes(x = PC1, y = PC2, label = rownames(scores))) +
# geom_hline(yintercept = 0, colour = "gray65") +
# geom_vline(xintercept = 0, colour = "gray65") +
# geom_text(colour = "tomato", alpha = 0.8, size = 4) +
# ggtitle("PCA plot of USA States - Crime Rates")
#####
# png(filename = sprintf('./pca/%s.pca.biplot.png',name),
# bg = "white")
# biplot(pca)
# dev.off()
# Creating eigenvariable in space
axis.nb <- which(summary.pca$importance["Cumulative Proportion",] >= proportion)[1]
eigenvariables <- predict(vars, pca, index = 1:axis.nb)
if (file.exists("./env") == FALSE) dir.create("./env")
writeRaster(eigenvariables,sprintf('./env/%s.eigenvariables.tif',name),overwrite=T)
}
@FelipeSBarros
Copy link
Author

Inserida variavel 'proportion', para definirmos qual proporcao de explicaçao (logo, quantos eixos iremos salvar) da PCA. proportion=entre 0 e 1

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment