#' @title Export Top PC Regions #' #' @description This function identifies a user-specified number of regions that contribute the most to an individual principal component. #' If there are any brain regions that contribute negatively to that a PC, it places those in a separate column. It then exports a #' .csv file that can be fed into the Matlab function CustomBrainRegionStack so that the anatomical organization of these brain regions #' can be visualized in 3D. Regions with positive scores will be colored green while regions with negative scores will be purple. #' @param PCAobject This is the output of your prcomp() function. It is a list that includes "rotation" #' @param PCnum This is which principal component you want to examine (e.g. PC1, PC2). Enter a number. #' @param num2show This is the number of regions in EACH color you want displayed on the graph. #' @export #' @examples export_top_PC_regions <- function(PCAobject, PCnum, num2show) { PCnum = as.numeric(PCnum) num2show = as.numeric(num2show) loading_scores_PC <- PCAobject$rotation[,PCnum] loading_scores_PC_ranked <- sort(loading_scores_PC, decreasing=TRUE) loading_scores_PC_ranked <- as_tibble(loading_scores_PC_ranked, rownames = "ROIname") top_regions_scores <- slice_head(loading_scores_PC_ranked, n=num2show) bottom_regions_scores <- slice_tail(loading_scores_PC_ranked, n=num2show) bottom_regions_filtered <- bottom_regions_scores %>% # only include bottom regions if their scores are actually <0 (subtract from the PC) filter(value < 0) %>% mutate(value = abs(value)) #...but Matlab needs positive numbers to graph brain_reg_columnar <- read_csv("293_brain_regions_formatted.csv") # THIS ONLY IS COMPATIBLE WITH THE MATLAB PROGRAM IF YOU USE THE FULL 293 BRAIN REGIONS colnames(brain_reg_columnar) <- "ROIname" tryJoin <- left_join(brain_reg_columnar, top_regions_scores) # fills in scores at corresponding brain regions tryJoin[is.na(tryJoin)] = 0 # replaces NAs with 0s tryJoin2 <- left_join(brain_reg_columnar, bottom_regions_filtered, by = "ROIname") # fills in scores at corresponding brain regions tryJoin2[is.na(tryJoin2)] = 0 # replaces NAs with 0s tryJoin$valueNeg <- tryJoin2$value #adds negative value column to main object tryJoin <- tryJoin %>% select(value, valueNeg) # gets rid of ROI names because they make Matlab unhappy filename <- paste("PC", as.character(PCnum), "_", as.character(num2show), "Regions_Custom_Map.csv", sep = "") #descriptive filename write_csv(tryJoin, filename) #write csv }