###################################################################
############### Module 6, Basics of data wrangling ################
###################################################################
## Lesson 13, Part 2: Reshaping your data and some other useful functions (reshaping)

# First load the tidyverse packages and then 
# upload the saved dataframe from the last part:
library(tidyverse)
covers_converted <- read_csv("data/covers_converted.csv")

###################################
##### RESHAPING DATAFRAMES
# Data that are ready for analysis have three particular
# features based on Hadley Wickham--one of the great
# masters of R and lead developer on the tidyverse
# packages:
# 1) Every column is its own variable
# 2) Every row is one observation
# 3) Every cell is one value
# See https://vita.had.co.nz/papers/tidy-data.pdf

covers_converted

covers_data_semifinal <- mutate(covers_converted,
                                cover_N = ifelse(covertype=="understory" & is.na(cover_N), 0, cover_N),
                                cover_E = ifelse(covertype=="understory" & is.na(cover_E), 0, cover_E),
                                cover_W = ifelse(covertype=="understory" & is.na(cover_W), 0, cover_W),
                                cover_S = ifelse(covertype=="understory" & is.na(cover_S), 0, cover_S),
                                cover_under = (cover_N + cover_E + cover_W + cover_S)/4) %>% 
  select(-(cover_N:cover_W))

covers_data_coalesced <- mutate(covers_data_semifinal, cover = coalesce(cover_mid, cover_under)) %>% 
  select(-(cover_mid:cover_under))

covers_data_fin <- pivot_wider(covers_data_coalesced, names_from=covertype, values_from=cover)

covers_data_nodupes <- group_by(covers_data_coalesced, island, plot, species, covertype) %>% 
  summarize(cover = mean(cover, na.rm=T))

covers_data_fin <- pivot_wider(covers_data_nodupes, names_from=covertype, values_from=cover, 
                               values_fill = 0)


covers_data_summ <- group_by(covers_data_fin, island, species) %>% 
  summarize(understory = mean(understory), midstory = mean(midstory)) %>% 
  ungroup()


island_soil <- read_csv("data/island_soil_data_raw.csv")
island_spatial <- read_csv("data/island_spatial_data_raw.csv")


covers_data_all <- left_join(covers_data_fin, island_spatial, by=c("island"="ISLAND")) %>% 
  left_join(island_soil) %>% 
  rename(area_ha = AREA_HA, distance_m = DIST_M, clay = Clay_perc, silt = Silt_perc, sand = Sand_perc)

###################################
##### SUMMARY
# - reshaping our dataframe using the pivot_wider function to
#   make each row become one species X site observation with values
#   for both understory and overstory cover

