Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

Practice working with time-series data, and plotly and leaflet packages, as well as some concepts in the Shiny app. The expected result is published on

Practice working with time-series data, andplotlyandleafletpackages, as well as some concepts in theShinyapp. The expected result is published on the following website:https://myazdi.shinyapps.io/PAssignment3/

Description

In this programming question, you will build a web app that visualizes thedata.csvdataset. The BPD arrests data is a list of arrests since 2014 provided by the Baltimore Police Department.

For parts a-e, you should create a new R script and run your code there. Once you can create the desired graphs, you will learn how to adjust your existing code for a Shiny web app and insert that code into theapp.Rin parts f and g;app.Ris an incomplete Shiny app provided to you. Your final result should be published onhttps://www.shinyapps.io/, andalso needyourapp.Rfile.

Supplemental Materials:data.csv,usholidays.csv, andapp.R

Submission:Your completedapp.Rand theURLof your web app.

a) Required libraries

You need the following packages for this assignment:

tidyversefor data wrangling and ggplot visualization

shinyfor building the web application visualizations

shinydashboardfor a dashboard web interface

leafletfor the interactive map visualization in the"Map"tab

DTfor the interactive data table in the"Data"tab

plotlyfor making the ggplot visualization in the"Plotly"tab interactive

b) Data wrangling

The goal of this part is to read and clean thedata.csvdataset. Follow the instructions below:

Store the dataset on a variable nameddata.

The dates of arrests are stored as characters in R. Use theas.Datefunction to convert

theArrestDatecolumn from characters to dates.

You will use theDTpackage later to show thedatadata frame on theDatatab. The

columnsLongitudeandLatitudeinclude the coordinates of arrests up to 10-12of a degree,

which makes it hard for users to read thetable. Round both theLongitudeandLatitude

columns to five digits.

c) Density graph

In this part, you will create a density graph illustrating age distribution for males and females (see the tabDensityon the published web app). The goal is to connect this graph with the slider input widget namedyearso that users can see the trend of density over different times. But for now, use the following instructions to write a code that creates the visualization for only the year 2014.

Use the following command inside thefilterfunction to filter the data for 2014:as.numeric(format(ArrestDate,'%Y')) == 2014

Pass the filtered data to the ggplot function.

As you may notice, the goal of this graph is not to compare the number of crimes by gender. The goal is to compare the density distribution within each gender, and that is whygeom_densitywill be used and notgeom_histgram. Usegeom_densityto create density functions. You can adjust the thickness of the lines by using the parametersize.

Add the text annotation "2014" to the background as you did in Programming Assignment 2.

Set thelabs,xlim, andylimof the graph properly.

The color legend shows the first letter of each gender (for example,"M"). Use the

scale_color_discretefunction to change each one to the spelled-out format (that is,

"Male").

You can decide the theme of your graph. I found the density unit confusing for users, so

I used the following command to remove some elements of they-axis: theme(axis.text.y=element_blank(), axis.ticks.y = element_blank(),

panel.grid.major = element_blank(), panel.grid.minor = element_blank(), panel.background = element_blank())

d) Plotly graph

Now you will practice how to convert aggplotfigure into an interactiveggplotlyfigure. As you can see in thePlotlytab in the published web app, the ultimate goal is to create an interactive line chart showing the number of arrest records in the dataset for each day over the past six years, so that users can explore the trend and outliers in the graph. Users should also be able to see holidays on the figure because a holiday can affect the number of arrests.

Read theusholidays.csvdataset, remove the first column (row index), and store it on theholidaysvariable.

Convert theDatecolumn from characters to dates.

I found the name of each holiday too long to be shown in the figure, so I decided to

use abbreviations instead. Use the following code to create a new column namedAbbto hold the abbreviatedHolidaycolumn. For example,"New Year's Day"will be changed to"NYD".

words=unique(holidays$Holiday)

Abb=c("NYD","MLKB","WaB", "MeD", "InD", "LaD", "CoD", "VeD", "ThD", "ChD", "NYD","MLKB","WaB")

holidays$Abb=holidays$Holiday for (i in 1:length(words)) {

holidays$Abb=str_replace(holidays$Abb,words[i],Abb[i]) }

Find the number of crimes for each day using the following command:

data %>% group_by(Date=ArrestDate) %>% summarise(N=n())

Use thefull_joinfunction to merge the data frame created above with theholidaysdata frame and store the combined frames on a variable nameddata_hol.

Use thegeom_lineandgeom_smoothfunctions to create a plot like the one in thePlotlytab and store the result on a variable namedf.

You do not need to change the theme of the figure. Use the following command to add the holiday points and texts on the figure:

f=f+geom_point(data= subset(data_hol, !is.na(Holiday)), color="purple")+ geom_text(data=subset(data_hol,!is.na(Holiday)), aes(x=Date, y=N, label=Abb))

Finally, you can convert yourggplotfigure to aggplotlyone using the following command:

ggplotly(f)

e) Map

Now you will create a heat map using theleafletpackage. As you can see in theMaptab in the published web app, the color of each rectangle shows the number of arrests in that area. If the rectangle is solid red, it means that the number of crimes in that rectangle has been very high since 2014, and a transparent box means the number of arrests has been very low.

The first step is to calculate the number of arrest records in each rectangle. In the map, the size of each rectangle is 0.001 degrees of latitude and 0.001 degrees of longitude. You can find which rectangle each arrest record will be assigned to by rounding latitude and longitude to three digits. For example, loc1: -76.6352, 39.3103 and loc2: -76.6349, 39.3101 will both be part of the same rectangle, which has a center of -76.635, 39.310.

Use the following command to find the frequency of each rectangle: loc_data= data %>%

group_by(lng=round(Longitude,3),lat=round(Latitude,3)) %>%

summarise(N=n())

Thelngandlatrepresent the center of each column. Using themutatefunction, add four columns (latL,latH,lngL, andlngH) toloc_datato show the range of latitude and longitude for each box. In other words,latL=lat-0.0005,latH=lat+0.0005,lngL=lng-0.0005, andlngH=lng+0.0005.

As in ggplot, we use the%>%operator to add different layers to theleafletmap. Use the command lines below to create a map:

m=loc_data %>% leaflet() %>% addTiles() %>%

setView(-76.6,39.31, zoom=12) %>%

addProviderTiles(providers$Stamen.Toner, group = "Toner")%>%

addLayersControl(baseGroups = c("Toner", "OSM"),

options = layersControlOptions(collapsed = FALSE))

The first line creates a simple map. The second line sets the zoom level and the center of the map. The third line adds a black-and-whitetileso users can see the heat map better. The fourth line adds the legend to the map so users can switch to the default tile Open Street Map (OSM) if they want to.

In the leaflet, you can add different elements and shapes to the map. You can see many examplesin this link:https://rstudio.github.io/leaflet/shapes.html. Read the description in the linked content and useaddRectanglesto create the rectangles. Because theloc_datadata frame has already been passed to the leaflet, you can use~to define a column. For example,lng1=~lngLmeans that the parameterlng1of theaddRectanglesfunction is set to columnlngLof theloc_datadata frame.

Once you create the rectangles, you may want to adjust them using the following parameters:fillOpacity = ~N/150, opacity = 0, fillColor = "red", label = ~N

fillOpacity = ~N/150,fillColor = "red"will handle the red color of the rectangles;opacity=0will remove the outlines of the rectangles; andlabel = ~Nshows the number of observations when users hover over a rectangle.

Now that you have completed this part of the assignment, we can move toapp.Rand try to complete both theuiandserverparts.

f) Completing the user interface(UI)

The user interface of the application is provided to you in theapp.Rfile. Putapp.R,data.csv, andusholidays.csvin an empty folder. Once you run theapp.Rfile, you should see thePlotly,Density, andMaptabs in your application. You will now complete theui. Please note that because theserverpart of the application is almost blank, you will not yet see the outputs, including the graphs, the map, and the table.

Change the title of the Shiny app fromShiny TitletoBPD Arrest.

Add the fourth tab, namedData, to the application with your choice of icon. As with the

rest of the tabs, you should add the tab once inside thesidebarMenufunction and once inside thetabItemsfunction. Please note that when you add a new parameter (element) to a function in theuipart, you need to separate your newly added parameter from other parameters with a comma.

Inside the fourthtabItem, use the command below to add a place to show thedatatable:

dataTableOutput("myTable")

Inside the fourthtabItem, add a link to the data source. Use thea()function with parametershref="https://data.baltimorecity.gov/Public-Safety/BPD-Arrests/3i3v-ibrt"andtarget="_blank". Thetargetparameter opens the dataset link in a new tab.

Run yourapp.Rto make sure that your app successfully shows the new tabDataand theData Sourcelink.

g) Completing the server in theapp.R

Copy your code from part b and paste it into the line afterserver <- function(input,

output, session) {in theapp.Rfile.

Cut the code for the first five bullets in part d (until creating thedata_holdata frame)

and paste it after the code from part b.

Copy the code for part c and paste it inside therenderfunction for theplot1output. Your graph is currently only working for the year2014. A slider namedyearin theuihas a value that can be set by users. Change any2014in your code toinput$yearso that your figure works for any year value entered by a user.

Run yourapp.R. Your application should run successfully. The figure in theDensitytab should change to show the value of the slider when you change the slider. Also, clicking theplaybutton under the slider will show an animation of how density will change over different years.

Copy the rest of the code for part d and paste it inside therenderfunction for theplot2output.

A checkbox namedholidayis in thePlotlytab. Users should be able to show/hide the holiday points by checking/unchecking this checkbox. In other words, thegeom_pointandgeom_textcode that we wrote before should be added to part f only wheninput$holiday==TRUE. Replace thegeom_pointandgeom_textcode with the following lines of code:

if(input$holiday==TRUE){

f=f+

geom_point(data= subset(data3, !is.na(Holiday)), color="purple")+ geom_text(data=subset(data3,!is.na(Holiday)), aes(x=ArrestDate, y=N, label=Abb), size=3) }

Runapp.Rand you should be able to see the time-series figure inside thePlotlytab. You should also be able to hide or show the holidays on the figure.

Copy the code for part e and paste it inside therenderfunction for themyMapoutput. Runapp.Rand you should be able to see the map inside theMaptab.

Learn from the structure of therenderfunctions that are provided in the code to write a properrenderfunction for thedatatableshown in theDatatab. Place yourrenderfunction after the code for themyMapoutput. Put the following command inside yourrenderfunction:

return(datatable(data, rownames= FALSE))

Runapp.Rand you should see thedatain theDatatab indatatableformat.

h) Publish your work on the shinyapps.io server

The steps to publish a Shiny app are as follows:

1,Run yourapp.R.

2,Click thePublishbutton at the top right of the page.

3,Click theAdd new accountlink at the top right of the page.

4,Click https://www.shinyapps.io/.

5,There is a box for pasting your tokens. Follow the instructions onModule 4 Dashboard Templates in Shinyto copy the tokens.

6,Name your application properly and click thePublishbutton.

7,Wait for RStudio to publish your app and keep the link to your web app. Do not forget to include theURLof your web app in the comments section when you submit yourapp.Rfile on Blackboard.

All needed datasets and partial app R. can be downloaded from the below links:

Data: https://www.dropbox.com/s/8ytyt9inyo6qjem/data.csv?dl=0

USholidays: https://www.dropbox.com/s/ngonk0ntizqh38r/usholidays.csv?dl=0

App R. : https://www.dropbox.com/s/uccqpstfwgzxbhp/app%283%29.R?dl=0

Step by Step Solution

There are 3 Steps involved in it

Step: 1

blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image

Step: 3

blur-text-image

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Recommended Textbook for

Calculus With Vectors

Authors: Jay S Treiman

1st Edition

3319094386, 9783319094380

More Books

Students also viewed these Mathematics questions

Question

=+b) Why is there no predictor variable for December?

Answered: 1 week ago