# ==========================================================
# Activity 30 - PCA III: two possums, and PERMANOVA
# Name:
# Date:
#
# Save as scripts/30_pca_possum.R
#
# HOW THIS FILE WORKS
# - Sections marked [ALREADY WRITTEN] are done for you:
#   just run them and answer the question on the activity page.
# - Every other section shows an EXAMPLE in the comments,
#   using made-up names like my_data. Read it, then type the
#   real code UNDER "Your turn", using today's data.
#
# Today is the same PCA recipe as Activity 18, plus one new test:
#   keep the numbers  ->  prcomp(scale. = TRUE)  ->
#   glue scores back on  ->  plot by group  ->  adonis2()
#
# Install once, before class: install.packages("vegan")
# ==========================================================


# ---- 1 Libraries and data [ALREADY WRITTEN] --------------
library(tidyverse)
library(plotly)
library(ggrepel)
library(leaflet)
library(vegan)

sites <- read_csv("data/possum_sites.csv")

possum_df <- read_csv("data/possum.csv") %>%
  left_join(sites, by = "site") %>%
  drop_na(foot_l)

invisible(NULL)


# ---- 2 Map the seven sites [ALREADY WRITTEN] -------------
# Run it. Where are the two species found?
species_pal <- colorFactor(c("darkorange", "purple"),
                           domain = sites$species)

leaflet(sites) %>%
  addTiles() %>%
  addCircleMarkers(~longitude, ~latitude,
                   color = ~species_pal(species),
                   label = ~site_name,
                   radius = 8, fillOpacity = 0.8) %>%
  addLegend(pal = species_pal, values = ~species)

invisible(NULL)


# ---- 3 Nine measurements and their correlations ----------
# EXAMPLE
#   my_num <- my_data %>%
#     select(first_col:last_col)   # a run of columns, in order
#
#   round(cor(my_num), 2)          # correlation matrix, 2 decimals
#
# Your turn: head_l through belly from possum_df;
# call it possum_meas




invisible(NULL)


# ---- 4 Run the PCA ---------------------------------------
# EXAMPLE
#   my_pca <- prcomp(my_num, center = TRUE, scale. = TRUE)
#   summary(my_pca)                # % variance per component
#
# Your turn: possum_meas; call it possum_pca




invisible(NULL)


# ---- 5 The loadings --------------------------------------
# EXAMPLE
#   round(my_pca$rotation[, 1:2], 2)   # PC1 and PC2 only
#
# Your turn: possum_pca




invisible(NULL)


# ---- 6 The big reveal ------------------------------------
# EXAMPLE
#   my_scores_df <- bind_cols(my_data, as_tibble(my_pca$x))
#
#   ggplot(my_scores_df, aes(x = PC1, y = PC2, colour = group)) +
#     geom_point(size = 2) +
#     coord_equal()
#
# Your turn: possum_df and possum_pca; call it possum_scores_df,
# colour by species




invisible(NULL)


# ---- 7 Prove the gap, then check the raw data ------------
# EXAMPLE
#   my_scores_df %>%
#     group_by(group) %>%
#     summarize(n = n(),
#               min_PC2 = min(PC2),
#               max_PC2 = max(PC2),
#               a = mean(a))
#
# Your turn: possum_scores_df by species. n, mean_PC1,
# min_PC2, max_PC2, then the means of ear_l, foot_l,
# tail_l and total_l




invisible(NULL)


# ---- 8 Hover to find the sites ---------------------------
# [ALREADY WRITTEN] the plot, with site names for hovering
hover_plot <- ggplot(possum_scores_df,
                     aes(x = PC1, y = PC2, colour = species,
                         text = paste(site_name, sex, "· animal", animal))) +
  geom_point(size = 2) +
  coord_equal()

# EXAMPLE
#   ggplotly(my_plot, tooltip = "text")
#
# Your turn: hover_plot




invisible(NULL)


# ---- 9 The biplot [ALREADY WRITTEN] ----------------------
# Run it. Which arrows point along the gap between species?
arrows_df <- as_tibble(possum_pca$rotation[, 1:2], rownames = "measure") %>%
  mutate(PC1 = PC1 * 4,
         PC2 = PC2 * 4)

ggplot(possum_scores_df, aes(x = PC1, y = PC2)) +
  geom_point(aes(colour = species), alpha = 0.5) +
  geom_segment(data = arrows_df,
               aes(x = 0, y = 0, xend = PC1, yend = PC2),
               arrow = arrow(length = unit(0.2, "cm"))) +
  geom_text_repel(data = arrows_df,
                  aes(x = PC1, y = PC2, label = measure), size = 3.2) +
  coord_equal()

invisible(NULL)


# ---- 10 PERMANOVA ----------------------------------------
# EXAMPLE
#   my_dist <- dist(scale(my_num))   # distances on scaled data
#
#   set.seed(42)                     # same permutations as everyone
#   adonis2(my_dist ~ group, data = my_data, permutations = 999)
#
# Your turn: possum_meas, then test species using possum_df;
# call the distances possum_dist




invisible(NULL)


# ---- 11 Check the spread ---------------------------------
# EXAMPLE
#   my_disp <- betadisper(my_dist, my_data$group)
#   set.seed(42)
#   permutest(my_disp)
#
# Your turn: possum_dist and possum_df$species;
# call it possum_disp




invisible(NULL)
