###################################################################
############### Module 6, Basics of data wrangling ################
###################################################################
## Lesson 11, Part 3: The split-apply-combine procedure:


# First load the tidyverse packages upload the tree data from the previous part of the lesson:
library("tidyverse")
tree_data <- read_csv("data/tree_data.csv")

###################################
##### SPLIT-APPLY-COMBINE (GROUP_BY and SUMMARIZE)
# One of the most common procedures for working with
# and preparing data for analyses is called the 
# split-apply-combine procedure.

tree_data

# 1) split the data into groups of each species on each island
# 2) calculate themean basal area of each of those groups by summing all 
# trunk areas, and then dividing by 0.05
# 3) combine these groups summaries back together

tree_summary <- group_by(tree_data, species, island) %>% 
  summarize(mean_BA_ha = sum(trunk_area_m2)/0.05,
            trees_per_samp = n()) %>% 
  ungroup()

tree_rel_size <- group_by(tree_data, island) %>% 
  mutate(relative_size = proportions(trunk_area_m2))

island_15 <- filter(tree_rel_size, island==15)

sum(island_15$relative_size)


###################################
##### SUMMARY
# - split-apply-combine procedure using group_by and summarize or mutate
#
# In the next lesson in this module we will go over combining datasets, but first
# a set of exercises to review this and the previous lessons.
