library(tidyverse)
library(ggplot2)
library(lubridate)
::opts_chunk$set(echo = TRUE, warning=FALSE, message=FALSE) knitr
Challenge 9
challenge_9
poultry
Creating a function
Read in data
set.seed(42)
<- read_csv('_data/poultry_tidy.csv')
poul head(poul)
# A tibble: 6 × 4
Product Year Month Price_Dollar
<chr> <dbl> <chr> <dbl>
1 Whole 2013 January 2.38
2 Whole 2013 February 2.38
3 Whole 2013 March 2.38
4 Whole 2013 April 2.38
5 Whole 2013 May 2.38
6 Whole 2013 June 2.38
Create Functions
Create date from year and month:
<- function(data) {
add_date <- mutate(data, Month_num = recode(Month, "January" = 1, "February" = 2, "March" = 3, "April" = 4, "May" = 5, "June" = 6, "July" = 7, "August" = 8, "September" = 9, "October" = 10, "November" = 11, "December" = 12))
data <- mutate(data, Date=make_date(Year, Month_num))
data return(data)
}
add_date(poul)
# A tibble: 600 × 6
Product Year Month Price_Dollar Month_num Date
<chr> <dbl> <chr> <dbl> <dbl> <date>
1 Whole 2013 January 2.38 1 2013-01-01
2 Whole 2013 February 2.38 2 2013-02-01
3 Whole 2013 March 2.38 3 2013-03-01
4 Whole 2013 April 2.38 4 2013-04-01
5 Whole 2013 May 2.38 5 2013-05-01
6 Whole 2013 June 2.38 6 2013-06-01
7 Whole 2013 July 2.38 7 2013-07-01
8 Whole 2013 August 2.38 8 2013-08-01
9 Whole 2013 September 2.38 9 2013-09-01
10 Whole 2013 October 2.38 10 2013-10-01
# … with 590 more rows
Plot a trend line given a product name:
<- function(data, product) {
plot_trend <- filter(data, Product == product)
data ggplot(data, aes(x = Date, y = Price_Dollar)) +
geom_line() +
ggtitle(paste('Price of Poultry (', product, ')'))
}
plot_trend(add_date(poul), 'Thighs')
plot_trend(add_date(poul), 'Whole')