###################################################################
############### Module 6, Basics of data wrangling ################
###################################################################
## Lesson 13, Part 4: Reshaping your data and some other useful functions (species by site matrix)

# First let's load the tidyverse package and the cleaned dataframe
# from the last lesson:
library(tidyverse)
covers_data_all <- read_csv("data/covers_data_all_part3.csv")

###################################
##### THE SPECIES BY SITE MATRIX

spp_by_site <- select(covers_data_all, island, species, understory)

spp_by_site_removed0 <- group_by(spp_by_site, species) %>% 
  filter(sum(understory) > 0) %>% 
  ungroup()

nrow(spp_by_site_removed0)

spp_by_site_wider <- pivot_wider(spp_by_site_removed0, names_from=species, values_from=understory)

islands <- spp_by_site_wider$island

spp_by_site_noisle <- select(spp_by_site_wider, -island)

spp_by_site_mat <- as.matrix(spp_by_site_noisle)

row.names(spp_by_site_mat) <- islands


apply(spp_by_site_mat, MARGIN=1, FUN=mean)


library("vegan")

set.seed(123)
nmds_plot <- metaMDS(comm = spp_by_site_mat)

plot(nmds_plot, display="sites", type="n")
text(nmds_plot)


###################################
##### SUMMARY
# - Using pivot_wider and as.matrix to create a species X site matrix
# - A quick barplot visualization of summary statistics
# - Using the species X site matrix for a quick ordination visualization

