###################################################################
############### Module 6, Basics of data wrangling ################
###################################################################
## Lesson 11, Part 2: The pipe operator and split-apply-combine:

# First reload the tidyverse packages and upload the island plant data:
library(tidyverse)
island_plants <- read_csv("data/island_veg_data_raw.csv")

# Also rerun our function for capitalizing species names so we can use it
# further down in the code:
cap_genus <- function(spp_name) {
  first_letter <- substr(spp_name, start=1, stop=1) #extract the first letter
  rest_of_name <- substr(spp_name, start=2, stop=nchar(spp_name)) # extract the rest
  first_let_cap <- toupper(first_letter)
  new_name <- paste(first_let_cap, rest_of_name, sep="")
  return(new_name)
}



###################################
##### PIPE OPERATOR
# A tool that will make it much easier to organize all of your
# data processing scripts.

tree_data_fin <- select(island_plants, island = Island, plot = Plot, date = `Date (mm/dd/yy)`,
                         covertype = CoverType, species = Species, diameter_cm = Over_Midstory) %>%
  # now filter out only the overstory data
  filter(covertype == "overstory") %>% 
  # add some important columns
  mutate(trunk_area_cm2 = pi*(diameter_cm/2)^2,
         trunk_area_m2 = trunk_area_cm2 * 0.0001,
         species = cap_genus(species),
         tree_size = ifelse(trunk_area_m2 < 0.1, "small", "large")) %>% 
  # remove the columns we don't need anymore
  select(-trunk_area_cm2, -diameter_cm)

### Extracting the undestory data:
under_data_fin <- select(island_plants, island = Island, species = Species, CoverType,
                         north = `Cover N`, east = `Cover E`,
                         south = `Cover S`, west = `Cover W`) %>% 
  mutate(species = cap_genus(species)) %>% 
  filter(CoverType == "understory") %>% 
  select(-CoverType)

write.csv(tree_data_fin, "data/tree_data.csv", row.names=F)







###################################
# - pipe operator
# - split-apply-combine procedure using group_by and summarize or mutate
