Skip to content

Commit

Permalink
Recompile exercises
Browse files Browse the repository at this point in the history
  • Loading branch information
mkfreeman committed Dec 11, 2018
1 parent 73e698d commit a4610d2
Show file tree
Hide file tree
Showing 19 changed files with 285 additions and 1 deletion.
2 changes: 1 addition & 1 deletion chapter-18-exercises/exercise-1/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ You will need to create and work with multiple files for this exercise, followin
## 1. Wrangle Data
You will need to implement a script to download the relevant movie review from the NY Times. Follow the instructions in the provided `exercise.R` file.

_This wrangling is the same as that used in Chapter 11 exercise-2; you can and should reuse that content._
_This wrangling is the same as that used in Chapter 14 exercise-2; you can and should reuse that content._

Note that you will need to register for an API key at **<https://developer.nytimes.com/signup>**. Save this in a file `apikey.R`, and be sure to modify your `.gitignore` file to list your `apikey.R` file as one to not be committed.

Expand Down
7 changes: 7 additions & 0 deletions chapter-19-exercises/exercise-5/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
# Exercise 5
In this exercise, you'll build a simple Shiny application that can communicate between a server and a user-interface. The final product will be a scatterplot in which you can select which columns of the `mpg` dataset to display, and how you want the graph to be rendered (using shiny widgets):

![final product scatterplot](imgs/final-plot.png)

To complete the exercise, you'll need to work in both the `ui.R` and `server.R` files in RStudio, and follow the instructions there.

Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
17 changes: 17 additions & 0 deletions chapter-19-exercises/exercise-5/server.R
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
### Exercise 5 ###

library(shiny)
library(ggplot2)
# Create a shiny server that creates a scatterplot.

# It should use an `input` with features: `x_var`, `y_var`, `color`, and `size`
# Save the result of `renderPlot` to output$scatter

# Store `x` and `y` values to plot


# Store the title of the graph in a variable


# Create ggplot scatter

24 changes: 24 additions & 0 deletions chapter-19-exercises/exercise-5/ui.R
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
# UI for scatterplot
library(shiny)

# Get a vector of column names (from `mpg`) to use as select inputs
select_values <- colnames(mpg)

# Create a shinyUI with a `fluidPage` layout

# Add a page header


# Add a `selectInput` for the `x` variable


# Add a `selectInput` for the `y` variable


# Add a `sliderInput` to set the `size` of each point


# Add a `selectInput` that allows you to select a color from a list of choices


# Plot the output with the name "scatter"
16 changes: 16 additions & 0 deletions chapter-19-exercises/exercise-6/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
# Exercise 6
In this exercise, you'll practice building an interactive Plotly map in a Shiny application.

As in previous exercises, you should fork and clone this repository, then follow the instructions below.

## server.R
Your `server.R` file already loads the data you need, as well as scripts for building a map. Inside your `shinyServer`, you should do the following:

- Replace the static input `'population'` with a dynamic value that comes from your UI

## ui.R
Your `ui.R` file already has a `tabPanel` built displaying your map. In this section, you should add another `tabPanel` for your scatter-plot by doing the following:

- Add a `selectInput` (with a proper id) that allows you to select a variable to map (`population`, `votes`, or `ratio`)

Also, make sure you look at the `build_map.R` file and **understand how it is using variables to make a dynamic application**.
1 change: 1 addition & 0 deletions chapter-19-exercises/exercise-6/data/electoral_college.csv
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
state,votes,populationAlabama,9,4858979Alaska,3,738432Arizona,11,6828065Arkansas,6,2978204California,55,39144818Colorado,9,5456574Connecticut,7,3590886Delaware,3,945934Florida,29,20271272Georgia,16,10214860Hawaii,4,1431603Idaho,4,1654930Illinois,20,12859995Indiana,11,6619680Iowa,6,3123899Kansas,6,2911641Kentucky,8,4425092Louisiana,8,4670724Maine,4,1329328Maryland,10,6006401Massachusetts,11,6794422Michigan,16,9922576Minnesota,10,5489594Mississippi,6,2992333Missouri,10,6083672Montana,3,1032949Nebraska,5,1896190Nevada,6,2890845New Hampshire,4,1330608New Jersey,14,8958013New Mexico,5,2085109New York,29,19795791North Carolina,15,10042802North Dakota,3,756927Ohio,18,11613423Oklahoma,7,3911338Oregon,7,4028977Pennsylvania,20,12802503Rhode Island,4,1056298South Carolina,9,4896146South Dakota,3,858469Tennessee,11,6600299Texas,38,27469114Utah,6,2995919Vermont,3,626042Virginia,13,8382993Washington,12,7170351 District of Columbia,3,672228West Virginia,5,1844128Wisconsin,10,5771337Wyoming,3,586107
Expand Down
1 change: 1 addition & 0 deletions chapter-19-exercises/exercise-6/data/state_codes.csv
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
code,stateAL,AlabamaAK,AlaskaAZ,ArizonaAR,ArkansasCA,CaliforniaCO,ColoradoCT,ConnecticutDE,DelawareFL,FloridaGA,GeorgiaHI,HawaiiID,IdahoIL,IllinoisIN,IndianaIA,IowaKS,KansasKY,KentuckyLA,LouisianaME,MaineMD,MarylandMA,MassachusettsMI,MichiganMN,MinnesotaMS,MississippiMO,MissouriMT,MontanaNE,NebraskaNV,NevadaNH,New HampshireNJ,New JerseyNM,New MexicoNY,New YorkNC,North CarolinaND,North DakotaOH,OhioOK,OklahomaOR,OregonPA,PennsylvaniaRI,Rhode IslandSC,South CarolinaSD,South DakotaTN,TennesseeTX,TexasUT,UtahVT,VermontVA,VirginiaWA,WashingtonWV,West VirginiaWI,WisconsinWY,Wyoming
Expand Down
32 changes: 32 additions & 0 deletions chapter-19-exercises/exercise-6/scripts/build_map.R
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
# BuildMap file: function that returns a plotly map
library(plotly)
library(stringr)

# BuildMap function: fill this in with a function that returns a map:
# Derived from: https://plot.ly/r/choropleth-maps/

build_map <- function(data, map_var) {
# give state boundaries a white border
l <- list(color = toRGB("white"), width = 2)

# specify some map projection/options
g <- list(
scope = 'usa',
projection = list(type = 'albers usa'),
showlakes = TRUE,
lakecolor = toRGB('white')
)

# Plot
p <- plot_geo(data, locationmode = 'USA-states') %>%
add_trace(
z = data[, map_var], text = ~state, locations = ~code,
color = data[, map_var], colors = 'Purples'
) %>%
colorbar(title = "Color Title") %>%
layout(
title = str_to_title(map_var),
geo = g
)
return(p)
}
24 changes: 24 additions & 0 deletions chapter-19-exercises/exercise-6/server.R
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
# server.R
library(dplyr)
library(shiny)
library(plotly)

# Read in data
source('./scripts/build_map.R')
df <- read.csv('./data/electoral_college.csv', stringsAsFactors = FALSE)
state_codes <- read.csv('./data/state_codes.csv', stringsAsFactors = FALSE)

# Join together state.codes and df
joined_data <- left_join(df, state_codes, by="state")

# Compute the electoral votes per 100K people in each state
joined_data <- joined_data %>% mutate(ratio = votes/population * 100000)

# Start shinyServer
shinyServer(function(input, output) {

# Render a plotly object that returns your map
output$map <- renderPlotly({
return(build_map(joined_data, "population"))
})
})
13 changes: 13 additions & 0 deletions chapter-19-exercises/exercise-6/ui.R
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
# Libraries
library(plotly)
library(shiny)

# ui.R
shinyUI(fluidPage(
mainPanel(
# Add a selectInput (with a proper id) that allows you to select a variable to map

# Plot the map
plotlyOutput("map")
)
))
24 changes: 24 additions & 0 deletions chapter-19-exercises/exercise-7/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
# Exercise 7
In this exercise, you'll practice building an a multi-tab Shiny application. The final product should look like this:

![scatter plot in shiny app](imgs/scatter.png)

The Map panel is already built for you to model. Your scatter panel should enable users to search for a state in the scatterplot.

As in previous exercises, you should fork and clone this repository, then follow the instructions below.

## server.R
Your `server.R` file already loads the data you need, as well as scripts for building a map and a scatter plot. Inside your `shinyServer`, you should do the following:

- Create a `scatter` property on your `output` object. That property should be a `renderPlotly` object that returns a scatterplot (`build_scatter`)
- Make sure to pass your data and search string (i.e., `input$search`) to your `build_scatter` function.

## ui.R
Your `ui.R` file already has a `tabPanel` built displaying your map. In this section, you should add another `tabPanel` for your scatter-plot by doing the following:

- Create a `tabPanel` to show your scatter plot
- Add a `titlePanel` to your tab
- Create a `sidebarLayout` for this tab (page)
- Create a `sidebarPanel` for your controls
- In your `sidebarPanel`, make a `textInput` widget for searching for a state in your scatter plot
- Create a `mainPanel`, in which you should display your plotly Scatter plot
1 change: 1 addition & 0 deletions chapter-19-exercises/exercise-7/data/electoral_college.csv
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
state,votes,populationAlabama,9,4858979Alaska,3,738432Arizona,11,6828065Arkansas,6,2978204California,55,39144818Colorado,9,5456574Connecticut,7,3590886Delaware,3,945934Florida,29,20271272Georgia,16,10214860Hawaii,4,1431603Idaho,4,1654930Illinois,20,12859995Indiana,11,6619680Iowa,6,3123899Kansas,6,2911641Kentucky,8,4425092Louisiana,8,4670724Maine,4,1329328Maryland,10,6006401Massachusetts,11,6794422Michigan,16,9922576Minnesota,10,5489594Mississippi,6,2992333Missouri,10,6083672Montana,3,1032949Nebraska,5,1896190Nevada,6,2890845New Hampshire,4,1330608New Jersey,14,8958013New Mexico,5,2085109New York,29,19795791North Carolina,15,10042802North Dakota,3,756927Ohio,18,11613423Oklahoma,7,3911338Oregon,7,4028977Pennsylvania,20,12802503Rhode Island,4,1056298South Carolina,9,4896146South Dakota,3,858469Tennessee,11,6600299Texas,38,27469114Utah,6,2995919Vermont,3,626042Virginia,13,8382993Washington,12,7170351 District of Columbia,3,672228West Virginia,5,1844128Wisconsin,10,5771337Wyoming,3,586107
Expand Down
1 change: 1 addition & 0 deletions chapter-19-exercises/exercise-7/data/state_codes.csv
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
code,stateAL,AlabamaAK,AlaskaAZ,ArizonaAR,ArkansasCA,CaliforniaCO,ColoradoCT,ConnecticutDE,DelawareFL,FloridaGA,GeorgiaHI,HawaiiID,IdahoIL,IllinoisIN,IndianaIA,IowaKS,KansasKY,KentuckyLA,LouisianaME,MaineMD,MarylandMA,MassachusettsMI,MichiganMN,MinnesotaMS,MississippiMO,MissouriMT,MontanaNE,NebraskaNV,NevadaNH,New HampshireNJ,New JerseyNM,New MexicoNY,New YorkNC,North CarolinaND,North DakotaOH,OhioOK,OklahomaOR,OregonPA,PennsylvaniaRI,Rhode IslandSC,South CarolinaSD,South DakotaTN,TennesseeTX,TexasUT,UtahVT,VermontVA,VirginiaWA,WashingtonWV,West VirginiaWI,WisconsinWY,Wyoming
Expand Down
Binary file added chapter-19-exercises/exercise-7/imgs/scatter.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
35 changes: 35 additions & 0 deletions chapter-19-exercises/exercise-7/scripts/build_map.R
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
# BuildMap file: function that returns a plotly map
library(plotly)
library(stringr)

# BuildMap function: fill this in with a function that returns a map:
# Derived from: https://plot.ly/r/choropleth-maps/

build_map <- function(data, map.var) {
# give state boundaries a white border
l <- list(color = toRGB("white"), width = 2)

# specify some map projection/options
g <- list(
scope = 'usa',
projection = list(type = 'albers usa'),
showlakes = TRUE,
lakecolor = toRGB('white')
)

# Make equation for map color / text
var.equation <- paste0('~', map.var)

# Plot
p <- plot_geo(data, locationmode = 'USA-states') %>%
add_trace(
z = data[,map.var], text = ~state, locations = ~code,
color = data[,map.var], colors = 'Purples'
) %>%
colorbar(title = "Color Title") %>%
layout(
title = str_to_title(map.var),
geo = g
)
return(p)
}
27 changes: 27 additions & 0 deletions chapter-19-exercises/exercise-7/scripts/build_scatter.R
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
# Build Scatter file: function that returns a plotly Scatter plot
library(plotly)
library(stringr)

### Build Scatter ###
build_scatter <- function(data, search = "", xvar = "population", yvar = "votes") {
# Get x and y max
xmax <- max(data[,xvar]) * 1.5
ymax <- max(data[,yvar]) * 1.5

# Filter data based on search
data <- data %>%
filter(grepl(search, state))

# Plot data
plot_ly(x = data[, xvar],
y = data[, yvar],
mode="markers",
marker = list(
opacity = .4,
size = 10
)) %>%
layout(xaxis = list(range = c(0, xmax), title = xvar),
yaxis = list(range = c(0, ymax), title = yvar)
) %>%
return()
}
25 changes: 25 additions & 0 deletions chapter-19-exercises/exercise-7/server.R
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
# server.R
library(dplyr)

# Read in data
source('./scripts/build_map.R')
source('./scripts/build_scatter.R')
df <- read.csv('./data/electoral_college.csv', stringsAsFactors = FALSE)
state_codes <- read.csv('./data/state_codes.csv', stringsAsFactors = FALSE)

# Join together state.codes and df
joined_data <- left_join(df, state_codes, by="state")

# Compute the electoral votes per 100K people in each state
joined_data <- joined_data %>% mutate(ratio = votes/population * 100000)

# Start shinyServer
shinyServer(function(input, output) {

# Render a plotly object that returns your map
output$map <- renderPlotly({
return(build_map(joined_data, input$mapvar))
})


})
36 changes: 36 additions & 0 deletions chapter-19-exercises/exercise-7/ui.R
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
# ui.R
library(shiny)
library(plotly)
shinyUI(navbarPage(
"Electoral College",
# Create a tab panel for your map
tabPanel(
"Map",
titlePanel("Electoral College Votes"),
# Create sidebar layout
sidebarLayout(

# Side panel for controls
sidebarPanel(

# Input to select variable to map
selectInput(
"mapvar",
label = "Variable to Map",
choices = list(
"Population" = "population",
"Electoral Votes" = "votes",
"Votes / Population" = "ratio"
)
)
),

# Main panel: display plotly map
mainPanel(
plotlyOutput("map")
)
)
)

# Create a tabPanel to show your scatter plot
))

0 comments on commit a4610d2

Please sign in to comment.