---
title: "Babynames (Parameterized)"
author: "Chester Ismay"
date: "October 14, 2015"
output: html_document
params:
  name: Jack
  year: 1990
---

```{r setup, include = FALSE, message = FALSE}
# This is where we load in all the packages we plan to use

# List of packages required for this analysis
pkg <- c("dplyr", "babynames")

# Check if packages are not installed and assign the
# names of the packages not installed to the variable new.pkg
new.pkg <- pkg[!(pkg %in% installed.packages())]

# If there are any packages in the list that aren't installed,
# install them
if (length(new.pkg)) {
  install.packages(new.pkg, repos = "http://cran.rstudio.com")
}

# Load the packages into R
library(dplyr)
library(babynames)
data("names", package = "babynames")
```

The `babynames` data comes from the Social Security Administration and gives information about the Top 1000 names given to children in the USA since 1880 (<http://www.ssa.gov/oact/babynames/limits.html>). Notice that the data is called `names` above when we load it from the `babynames` package, but you will receive an error if you try to use `names` as your data frame before the `%>%`.  This is just a quirk with how Hadley labeled things. 

#### Problem

Identify how many people were born with **parameterized first name** (`r params$name`) in the US in **paramaterized year** (`r params$year`).

```{r example}
entered_name <- params$name
entered_year <- params$year
result <- babynames %>% filter(name == entered_name) %>%
  filter(year == entered_year) %>%
  summarize(count = sum(n))
result
```

We can reference values stored in R directly in your text.  

**Something like this:**

We have determined that (of the top 1000 names) in `r entered_year`, there were `r format(result, big.mark = ',')` babies born in the US with the first name '`r entered_name`'.

Additionally, we can produce output conditional on results using the `ifelse` function in R:

`r ifelse(result < 500, "The name you entered was not very popular in that year.", "")`

**One more tweak**:  You can use the `paste0` function to create a sentence based on values.

`r ifelse(result < 500, paste0("The name '", entered_name, "' was not very popular in ", entered_year, "."), "What a popular name!")`

### Try this!

You'll need to `Run Current Chunk` here to get the desired output.

```{r try_this, eval = FALSE}
names_array <- c("Hayden", "Justin", "Doug", "Mary")
years_array <- rep(1950, times = length(names_array))
rm(params)
for(i in 1:length(names_array)){
  rmarkdown::render("babynames_parameterized.Rmd", 
                  params = list(name = names_array[i], year = years_array[i]),
                  output_dir = "results",
                  output_file = paste0(names_array[i], "_", years_array[i], ".html")
  )
}
```

