I have data structured like this:
set.seed(123)
dat1 <- data.frame(State = rep(c("NY","MA","FL","GA"), each = 10),
Loc = rep(c("a","b","c","d","e","f","g","h"),each = 5),
ID = rep(c(1:10), each = 2),
var1 = rnorm(200),
var2 = rnorm(200),
var3 = rnorm(200),
var4 = rnorm(200),
var5 = rnorm(200))
I am using the FactoMineR and factoextra packages for PCA. I am writing the following function to produce summary outputs and plots for PCA:
pfun <- function(dat, cols, ncp){
res <- PCA(dat[,cols], scale.unit = T, ncp = ncp, graph = F)
eigs<-round(res$eig, 2)
scree <- fviz_eig(res, addlabels = T)
contribplot<-corrplot(get_pca_var(res)$contrib, is.corr = F)#variable contributions to each pc
cos2plot<-corrplot(pca.vars$cos2, is.corr=F)#quality of var representation in each pc
output<- list(eigs, scree, contribplot, cos2plot)
return(output)
}
pfun(dat = cdatsq, cols = 7:13, ncp = 7)
The function works fine so far, but I would also like for it to produce biplots and variable contribution plots for each number/combination of principle components that the function determines to have eigenvalues less than or equal to 1. For instance, I tried to use num <- sum(eigs[,1]>=1, na.rm = TRUE)#for the number of pcs to keep and plot with a for loop in the function:
for(i in 1:sum(eigs[,1]>=1, na.rm = TRUE)){
fviz_contrib(res, choice = "var", axes = i, top = 10)
}
This did not work, how can I make these print with the rest of the output? Additionally, I wanted to use fviz_pca_biplot() to produce biplots for each combination of principle components within the bounds of sum(eigs[,1]>=1, na.rm = TRUE). Outside of a function, one plot call would look like this:
#example shown for PC2:PC3 with points labeled by `Loc`
fviz_pca_biplot(res, axes = c(2,3), geom.ind = "point", pointsize=0, repel = T)+
ggtitle("plot for PC2:PC3")+
geom_text(aes(label = paste0(dat1$Loc)), alpha = 0.5, size = 3, nudge_y = 0.1, show.legend = FALSE)
But within the function, how can I specify "all combinations of" the principle components within the bounds of sum(eigs[,1]>=1, na.rm = TRUE) (i.e., there will be a plot for PC1:PC2, PC2:PC3, and so on)?
Ideally, I would like to facet the biplots into separate grids for each grouping variable (e.g., a page where the biplot points are colored by State and a page where they are colored by Loc).




