###################################################################
############### Module 6, Basics of data wrangling ################
###################################################################
## Lesson 11, Part 1: Mutating data: mutate function:


###################################
##### SELECT AND FILTER REVIEW

library("tidyverse")

island_plants <- read_csv("data/island_veg_data_raw.csv")

names(island_plants)

overstory_data <- select(island_plants, island = Island, plot = Plot, date = `Date (mm/dd/yy)`,
                         covertype = CoverType, species = Species, diameter_cm = Over_Midstory)
unique(overstory_data$covertype)

overstory_data <- filter(overstory_data, covertype == "overstory")

###################################
##### MUTATE FUNCTION
# Create new columns and modify existing ones using the mutate function.

tree_data_fin <- mutate(overstory_data,
                        trunk_area_cm2 = pi*(diameter_cm/2)^2,
                        trunk_area_m2 = trunk_area_cm2 * 0.0001)

tree_data_fin <- select(tree_data_fin, -trunk_area_cm2, -diameter_cm)

# function for capitalizing the genus:
# 1) extract the first character of each scientific name
# 2) extract the rest of the name
# 3) make that first letter capital.
# 4) recombine the first capital letter with the rest of the name
# 5) return the new name

spp_name <- "pinus taeda"

cap_genus <- function(spp_name){
  #1)
  first_char <- substr(spp_name, start = 1, stop = 1)
  #2)
  rest_of_name <- substr(spp_name, start = 2, stop = nchar(spp_name))
  #3) 
  first_char_cap <- toupper(first_char)
  #4) 
  new_name <- paste(first_char_cap, rest_of_name, sep="")
  #5)
  return(new_name)
}

cap_genus("taraxacum officinale")

tree_data_fin <- mutate(tree_data_fin, species = cap_genus(species))

hist(tree_data_fin$trunk_area_m2, breaks=20)

tree_data_fin <- mutate(tree_data_fin, 
                        tree_size = ifelse(trunk_area_m2 < 0.1, "small", "large"))


###################################
##### SUMMARY
# - reviewed select and filter
# - mutate function

