9
library(shiny) library(shinythemes) library(dplyr) library(ggplot2) library(radiant.data) library(radiant.model) library(ggvis) library(ggplot2) library(ggmap) library(gridExtra) library(googleVis) library(plotly) library(DT) library(leaflet) # library(radiant.design) # library(radiant.basics) # library(radiant.multivariate) # library(mvtnorm) # library(radiant) # Reading in the required datafiles from the source time.parameter <- read.csv("timeparameter.csv") safety.parameter <- read.csv("safetyparameter.csv") cost.parameter <- read.csv("costparameter.csv") cost.parameter.dropped <- cost.parameter[,c(-6,-7,-8)] final.results <- read.csv("Finalresults.csv") final.safety.results <- read.csv("Finalsafetyresults.csv") final.cost.results <- read.csv("Finalcostresults.csv") final.time.results <- read.csv("Finaltimeresults.csv") final.weighted.data <- read.csv("Finalweighteddata1.csv") all.location <- read.csv("Location.csv") locations <- all.location[1:30,] locations$Location <- gsub(",",":",locations$Location) placeNames <- as.character(locations$Intersection) plotData <- data.frame(name = placeNames, latLong = unlist(locations$Location)) volume.by.year <- read.csv("~/Desktop/firstpanel/volumeByYear.csv") volume.by.year.1 <- volume.by.year[,1:10] volumeByYear <- read.csv("~/Desktop/firstpanel/volumeByYear.csv") volumeByYear2013 <- volumeByYear[1:30,] social.good.2016 <- read.csv("~/Desktop/firstpanel/socialgood.csv") final.weighted.data <- read.csv("Finalweighteddata1.csv") final.weighted.data.table <- final.weighted.data[,c("Intersection","Time.100","Cost.100","Safety.100","Total.100", "Rank")] radius <- final.weighted.data$size*8

R (Shiny Package) - Server Side Code for Decision Support System

Embed Size (px)

Citation preview

Page 1: R (Shiny Package) - Server Side Code for Decision Support System

library(shiny)

library(shinythemes) library(dplyr)

library(ggplot2) library(radiant.data)

library(radiant.model) library(ggvis)

library(ggplot2) library(ggmap) library(gridExtra) library(googleVis) library(plotly) library(DT) library(leaflet) # library(radiant.design)

# library(radiant.basics)

# library(radiant.multivariate) # library(mvtnorm)

# library(radiant) # Reading in the required datafiles from the source time.parameter <- read.csv("timeparameter.csv") safety.parameter <- read.csv("safetyparameter.csv") cost.parameter <- read.csv("costparameter.csv") cost.parameter.dropped <- cost.parameter[,c(-6,-7,-8)] final.results <- read.csv("Finalresults.csv") final.safety.results <- read.csv("Finalsafetyresults.csv") final.cost.results <- read.csv("Finalcostresults.csv")

final.time.results <- read.csv("Finaltimeresults.csv") final.weighted.data <- read.csv("Finalweighteddata1.csv")

all.location <- read.csv("Location.csv") locations <- all.location[1:30,]

locations$Location <- gsub(",",":",locations$Location) placeNames <- as.character(locations$Intersection) plotData <- data.frame(name = placeNames, latLong = unlist(locations$Location)) volume.by.year <- read.csv("~/Desktop/firstpanel/volumeByYear.csv") volume.by.year.1 <- volume.by.year[,1:10]

volumeByYear <- read.csv("~/Desktop/firstpanel/volumeByYear.csv") volumeByYear2013 <- volumeByYear[1:30,]

social.good.2016 <- read.csv("~/Desktop/firstpanel/socialgood.csv") final.weighted.data <- read.csv("Finalweighteddata1.csv")

final.weighted.data.table <- final.weighted.data[,c("Intersection","Time.100","Cost.100","Safety.100","Total.100", "Rank")]

radius <- final.weighted.data$size*8

Page 2: R (Shiny Package) - Server Side Code for Decision Support System

color <- colorFactor(c("#00FF00","#FFFF00","#FF0000"), final.weighted.data$DDI.Requirement)

popus <- paste(sep = "<br/>", "Intersection:",

final.weighted.data$Intersection, "Ranking:",

final.weighted.data$Rank, "Total Score:",

final.weighted.data$Total.100) m <- leaflet(final.weighted.data) %>% addTiles('http://{s}.basemaps.cartocdn.com/dark_all/{z}/{x}/{y}.png', attribution='Map tiles by <a href="http://stamen.com">Stamen Design</a>, <a href="http://creativecommons.org/licenses/by/3.0">CC BY 3.0</a> &mdash; Map data &copy; <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a>') m %>% setView(-96.8, 32.7833333, zoom = 8) m %>% addCircles(lng= ~lng, lat= ~lat , popup=popus, weight = 7, radius=radius, color=

~color(DDI.Requirement), stroke = TRUE, fillOpacity = 0.8)

# # Variables that can be put on the x and y axes # axis_vars <- c( # "Time" = "Time", # "Cost" = "Cost", # "Safety" = "Safety", # "Total" = "Total", # "Ranking" = "Ranking" # )

# ------------- GRAPHS BASIC -------------------- #

ddi.distance <- c(2,3,8,10,12,14) ddi.cost.per.mile <- c(2000000,8000000,16000000,20000000,24000000,28000000)

cost.of.construction.per.mile <- data.frame(ddi.distance, ddi.cost.per.mile) intersections <- c('DNT/635', 'DNT/Alpha', 'DNT/Spring Valley', 'DNT/Beltine', 'DNT/Keller Springs', 'DNT/Trinity MIlls', 'DNT/Frankford','DNT/PGBT','DNT/Park','DNT/Parker', 'DNT/Windhaven','DNT/Spring Creek','DNT/Legacy','DNT/SRT','DNT/Gaylord','PGBT/Preston','SRT/Preston','PGBT/75',

'PGBT/Royal Rd','PGBT/Old Denton Rd','PGBT/Independence Rd','PGBT/SH 78','SRT/McArthur Blvd','SRT/Hebron Pkwy','SRT/Parker Rd','SRT/Marchant Blvd','SRT/Josey

Ln','SRT/Parkwood','SRT/Coit Rd','SRT/Stacy Rd') type.of.intersection <- c("cloverleaf", "flared", "flared","flared","flared","flared","flared",

"cloverleaf", "flared", "flared", "flared", "flared", "flared", "cloverleaf", "flared","flared", "flared","cloverleaf","flared","flared","flared","cloverleaf",

"flared","flared","flared","flared","flared","flared","flared","flared")

Page 3: R (Shiny Package) - Server Side Code for Decision Support System

intersection.type <- data.frame(intersections, type.of.intersection)

intersection.type$points <- ifelse(intersection.type$type.of.intersection=="cloverleaf", 74.5, 77.8)

# Calculating the increase in points if a DDI (83.6) is built based on the type of intersection intersection.type$ddi <- ifelse(intersection.type$type.of.intersection=="cloverleaf", 9.1, 5.8)

# Conditional statement to see which intersections can be converted to a DDI intersection.type$ddi.possibility <- ifelse(intersection.type$type.of.intersection=="cloverleaf",

"NO","YES") intersection.type.modified <- subset(intersection.type, ddi.possibility == "YES") # ------------- GRAPHS BASIC -------------------- # # ------------------------- Creating Outputs required for PANEL 1 ---------------- # # Creating an output in the data tab

shinyServer(function(input, output) {

output$time.data <- renderTable({ colm <- as.numeric(input$time.parameters)

time.parameter[colm] }) output$safety.data <- renderTable({ colm <- as.numeric(input$safety.parameters) safety.parameter[colm] }) output$cost.data <- renderTable({ colm <- as.numeric(input$cost.parameters) cost.parameter[colm]

})

# ------------------------- END OF TABLE RENDERING ---------------- #

# ------------------------- Creating Outputs required for PANEL 2 ---------------- # # Filter data based on selections output$table <- DT::renderDataTable(DT::datatable({ data <- time.parameter

if (input$intersections != "All") { data <- data[data$Intersections == input$intersections,]

} if (input$exist.lane.length != "All") {

data <- data[data$Existing.Lane.Length == input$exist.lane.length,] }

if (input$left.turns != "All") {

Page 4: R (Shiny Package) - Server Side Code for Decision Support System

data <- data[data$Lefts == input$left.turns,]

} data

}))

# ------------------------- END OF TABLE RENDERING for PANEL 2 ---------------- #

# ------------------------- BEGIN PANEL 3 --------------------------- # result <- explore(dataset = "time.parameter", vars = c("X..of.left.turns", "Hours.wasted.in.traffic", "Annual.hours.wasted.in.traffic", "Average.Daily.Total.Traffic", "Speed.Limit", "Existing.Lane.Length"), fun = c("length", "mean_rm", "sd_rm", "min_rm", "max_rm"), nr = 8) time.table <- result$tab

output$time.table <- renderTable({

colm <- as.numeric(unlist(input$time.summary)) time.table[colm]

} ) result <- explore(dataset = "cost.parameter.dropped", vars = c("Hours.wasted.in.Traffic", "Existing.Lane.Length", "Shoulder.Width"), fun = c("length", "mean_rm", "sd_rm", "min_rm", "max_rm"), nr = 8) cost.table <- result$tab output$cost.table <- renderTable({

colm <- as.numeric(unlist(input$cost.summary)) cost.table[colm]

} )

result <- explore(dataset = "safety.parameter", vars = c("Number.of.right.lanes", "Number.of.left.lanes", "Percentage.of.left.turns", "Average.daily.total.traffic", "Movements", "Shoulder.width", "Percentage.of.trucks", "Clearance", "Speed.Limit"), fun = c("length", "mean_rm", "sd_rm", "min_rm", "max_rm"), nr = 8)

safety.table <- result$tab

output$safety.table <- renderTable({

colm <- as.numeric(unlist(input$safety.summary)) safety.table[colm]

}

Page 5: R (Shiny Package) - Server Side Code for Decision Support System

)

# ------------------------- END PANEL 3 --------------------------- #

# ------------------------- START PANEL 4 --------------------------- #

result <- evalreg(dataset = "time.parameter", pred = c("X..of.left.turns",

"Average.Daily.Total.Traffic", "Speed.Limit"), rvar = "Annual.hours.wasted.in.traffic", train = "All") # summary(result) # plot("result") output$result <- renderPrint({summary(result)}) result.1 <- evalreg(dataset = "safety.parameter", pred = c("Shoulder.width","Percentage.of.trucks", "Clearance"), rvar = "Average.daily.total.traffic",

train = "All")

output$result.1 <- renderPrint({summary(result.1)})

# ------------------------- END PANEL 4 --------------------------- # # PLOT FOR TIME AND COST output$plot1 <- renderPlot({ plot(final.weighted.data$Time.100, final.weighted.data$Cost.100, xlab = "Weighted Time Results", ylab = "Weighted Cost Results", type = "p") }) # Verbatim Text Output for COST - TIME output$info <- renderText({

xy_str <- function(e) { if(is.null(e)) return("NULL\n")

paste0("x=", round(e$x, 4), " y=", round(e$y, 4), "\n") }

xy_range_str <- function(e) { if(is.null(e)) return("NULL\n") paste0("xmin=", round(e$xmin, 4), " xmax=", round(e$xmax, 4), " ymin=", round(e$ymin, 4), " ymax=", round(e$ymax, 4)) }

paste0(

"click: ", xy_str(input$plot_click), "dblclick: ", xy_str(input$plot_dblclick),

"hover: ", xy_str(input$plot_hover), "brush: ", xy_range_str(input$plot_brush)

)

Page 6: R (Shiny Package) - Server Side Code for Decision Support System

})

# PLOT FOR TIME AND SAFETY

output$plot2 <- renderPlot({ plot(final.weighted.data$Time.100, final.weighted.data$Safety.100, xlab = "Weighted Time

Results", ylab = "Weighted Safety Results", type = "p") })

# Verbatim Text Output for SAFETY - TIME output$info1 <- renderText({ xy_str <- function(e) { if(is.null(e)) return("NULL\n") paste0("x=", round(e$x, 4), " y=", round(e$y, 4), "\n") } xy_range_str <- function(e) {

if(is.null(e)) return("NULL\n")

paste0("xmin=", round(e$xmin, 4), " xmax=", round(e$xmax, 4), " ymin=", round(e$ymin, 4), " ymax=", round(e$ymax, 4))

} paste0( "click: ", xy_str(input$plot_click), "dblclick: ", xy_str(input$plot_dblclick), "hover: ", xy_str(input$plot_hover), "brush: ", xy_range_str(input$plot_brush) ) })

# PLOT FOR COST AND SAFETY output$plot3 <- renderPlot({

plot(final.weighted.data$Cost.100, final.weighted.data$Safety.100, xlab = "Weighted Cost Results", ylab = "Weighted Safety Results", type = "p")

}) # Verbatim Text Output for SAFETY - COST output$info2 <- renderText({ xy_str <- function(e) {

if(is.null(e)) return("NULL\n") paste0("x=", round(e$x, 4), " y=", round(e$y, 4), "\n")

} xy_range_str <- function(e) {

if(is.null(e)) return("NULL\n") paste0(" xmin=", round(e$xmin, 4), " xmax=", round(e$xmax, 4),

" ymin=", round(e$ymin, 4), " ymax=", round(e$ymax, 4))

Page 7: R (Shiny Package) - Server Side Code for Decision Support System

}

paste0(

"click: ", xy_str(input$plot_click), "dblclick: ", xy_str(input$plot_dblclick),

"hover: ", xy_str(input$plot_hover), "brush: ", xy_range_str(input$plot_brush)

) }) # --------------------------------------------------------- output$gvis <- renderGvis({ gvisMotionChart(volume.by.year.1, idvar = "Intersection..SB...NB.", timevar = "Year") })

output$socialgood <- renderGvis({ gvisMotionChart(social.good.2016, idvar = "Intersections",

timevar = "Year") })

output$x <- renderGvis({ gvisMap(volume.by.year.1, locationvar = "Location", tipvar = c("Intersection..SB...NB."), options=list(showTip=TRUE, showLine=TRUE, enableScrollWheel=TRUE, mapType='normal', useMapTypeControl=TRUE, width=800,height=400)) }) # --------------------------------------------------------- threed.plot <- plot_ly(x = volumeByYear2013$One.way.Traffic.Volume.am, y =

volumeByYear2013$One.way.Traffic.Volume.md, z = volumeByYear2013$One.way.Traffic.Volume.pm, type = "scatter3d", color =

volumeByYear2013$Intersection..SB...NB., colors = "Set1", width = 600, height = 400) %>% layout(title = "Traffic Comparison by Intersection", scene = list(xaxis = list(title = "Peak AM

Traffic"), yaxis = list(title = "Peak PM Traffic"), zaxis = list(title= "Peak MD Traffic"))) output$plot_ly <- renderPlotly({ threed.plot })

output$hover_ly <- renderPrint({

d <- event_data("plotly_hover") if (is.null(d)) "Hover events appear here (unhover to clear)" else d

})

output$click_ly <- renderPrint({

Page 8: R (Shiny Package) - Server Side Code for Decision Support System

d <- event_data("plotly_click")

if (is.null(d)) "Click events appear here (double-click to clear)" else d })

# ---------------------------------------------------------

# ---------------------------------------------------------

datasetInput <- reactive({ switch(input$dataset, "Time.Data" = time.parameter, "Cost.Data" = cost.parameter, "Safety.Data" = safety.parameter, "Social.Good" = social.good.2016) })

output$downloadData <- downloadHandler( filename = function() { paste(input$dataset, '.csv', sep='') },

content = function(file) { write.csv(datasetInput(), file) } ) # --------------------------------------------------------- final.weighted.data <- read.csv("Finalweighteddata1.csv") radius <- final.weighted.data$size*8

color <- colorFactor(c("#00FF00","#FFFF00","#FF0000"), final.weighted.data$DDI.Requirement)

popus <- paste(sep = "<br/>", "Intersection:",

final.weighted.data$Intersection, "Ranking:", final.weighted.data$Rank, "Total Score:", final.weighted.data$Total.100)

output$map <- renderLeaflet({ m <- leaflet(final.weighted.data) %>%

addTiles('http://{s}.basemaps.cartocdn.com/dark_all/{z}/{x}/{y}.png', attribution='Map tiles by <a href="http://stamen.com">Stamen Design</a>, <a

href="http://creativecommons.org/licenses/by/3.0">CC BY 3.0</a> &mdash; Map data &copy; <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a>')

m %>% setView(-96.8, 32.7833333, zoom = 8)

Page 9: R (Shiny Package) - Server Side Code for Decision Support System

m %>% addCircles(lng= ~lng, lat= ~lat , popup=popus, weight = 7, radius=radius, color=

~color(DDI.Requirement), stroke = TRUE, fillOpacity = 0.8) })

# ---------------------------------------------------------

output$maps.table <- DT::renderDataTable(final.weighted.data.table, filter = 'top', server =

FALSE) } )