knitr::opts_chunk$set(echo = TRUE)
knitr::opts_chunk$set(
  collapse = TRUE,
  comment = "#>"
)
library(HW4)
library(tidyverse)
#get our data 

data(precip)
data(temp)

Functions find_anom and find_precip_anom: Precipiation and temperature anomalies

#this function looks at temperature and precipitation data and returns the minumum and maximum values along with the correspending year each value occured in 


# example data for precipitation
precip_data =
    data.frame(
        Date = c(1:16),
        Value = c(1:16),
        Anomaly = c(1:16)
    )
precip_data

find_precip_anom(precip_data)

#example data for temperature 

temp_data =
    data.frame(
        Date = c(1:16),
        Value = c(1:16),
        Anomaly = c(1:16)
    )

temp_data

find_anom(temp_data)

function: crop_loss

#this function uses climate and temerature data to compute the biggest drought and wet years by location

#climate data
temp = rnorm(500, mean = 30, sd = 10)
dates = seq(from = 1920, to = 2010, by = 10)
locations = c("Willamette", "Central_Valley", "Napa", "Columbia_Valley","Central_Coast")
ag_temp <- matrix(temp, nrow = 10, ncol = 5,
                       dimnames = list(c(dates), c(locations)))
#precip data
rain = rnorm(500, mean = 1.5, sd = .5)
dates = seq(from = 1920, to = 2010, by = 10)
locations = c("Willamette", "Central_Valley", "Napa","Columbia_Valley","Central_Coast")
ag_precip <- matrix(rain, nrow = 10, ncol = 5,
                       dimnames = list(c(dates), c(locations)))

function: measure_river_flow

#measures river flow given precipitation and year data 


measure_river_flow = function(precip, year) {

  riverflow <- precip %>%
    dplyr::mutate(river_flow = Value*7500) %>%
    filter(Date %in% year)

  x <- mean(riverflow$river_flow)

  return(x)
} 

function: count cow deaths

#uses temperature to calculate cow deaths 

count_cow_deaths = function(temp) {


  cows_df <- temp %>%
    mutate(cow_deaths = case_when(Value >= 50 ~ Value*100,
                                  Value < 50 ~ Value*20),
           lost_revenue = cow_deaths*4000) %>%
    group_by(Date) %>%
    summarise(cow_mortality = sum(cow_deaths, na.rm = TRUE),
              lost_revenue = sum(lost_revenue, na.rm = TRUE)) %>%
    ungroup()

  return(cows_df)

}


kellyodion/ESM262-function-HW documentation built on June 14, 2019, 12:31 p.m.