SlideShare a Scribd company logo
1 of 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
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")
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") {
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]
}
)
# ------------------------- 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("NULLn")
paste0("x=", round(e$x, 4), " y=", round(e$y, 4), "n")
}
xy_range_str <- function(e) {
if(is.null(e)) return("NULLn")
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 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("NULLn")
paste0("x=", round(e$x, 4), " y=", round(e$y, 4), "n")
}
xy_range_str <- function(e) {
if(is.null(e)) return("NULLn")
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("NULLn")
paste0("x=", round(e$x, 4), " y=", round(e$y, 4), "n")
}
xy_range_str <- function(e) {
if(is.null(e)) return("NULLn")
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)
)
})
# ---------------------------------------------------------
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({
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)
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)
}
)

More Related Content

What's hot

Clustering com numpy e cython
Clustering com numpy e cythonClustering com numpy e cython
Clustering com numpy e cython
Anderson Dantas
 
Building Real Time Systems on MongoDB Using the Oplog at Stripe
Building Real Time Systems on MongoDB Using the Oplog at StripeBuilding Real Time Systems on MongoDB Using the Oplog at Stripe
Building Real Time Systems on MongoDB Using the Oplog at Stripe
MongoDB
 
Map/reduce, geospatial indexing, and other cool features (Kristina Chodorow)
Map/reduce, geospatial indexing, and other cool features (Kristina Chodorow)Map/reduce, geospatial indexing, and other cool features (Kristina Chodorow)
Map/reduce, geospatial indexing, and other cool features (Kristina Chodorow)
MongoSF
 
Postgres performance for humans
Postgres performance for humansPostgres performance for humans
Postgres performance for humans
Craig Kerstiens
 
Palestra sobre Collections com Python
Palestra sobre Collections com PythonPalestra sobre Collections com Python
Palestra sobre Collections com Python
pugpe
 

What's hot (19)

Optimization and Mathematical Programming in R and ROI - R Optimization Infra...
Optimization and Mathematical Programming in R and ROI - R Optimization Infra...Optimization and Mathematical Programming in R and ROI - R Optimization Infra...
Optimization and Mathematical Programming in R and ROI - R Optimization Infra...
 
Strategic autovacuum
Strategic autovacuumStrategic autovacuum
Strategic autovacuum
 
PostgreSQL Procedural Languages: Tips, Tricks and Gotchas
PostgreSQL Procedural Languages: Tips, Tricks and GotchasPostgreSQL Procedural Languages: Tips, Tricks and Gotchas
PostgreSQL Procedural Languages: Tips, Tricks and Gotchas
 
Stop Guessing and Start Measuring - Benchmarking Practice (Poly Version)
 Stop Guessing and Start Measuring - Benchmarking Practice (Poly Version) Stop Guessing and Start Measuring - Benchmarking Practice (Poly Version)
Stop Guessing and Start Measuring - Benchmarking Practice (Poly Version)
 
How fast is it really? Benchmarking in Practice (Ruby Version)
How fast is it really? Benchmarking in Practice (Ruby Version)How fast is it really? Benchmarking in Practice (Ruby Version)
How fast is it really? Benchmarking in Practice (Ruby Version)
 
New Tuning Features in Oracle 11g - How to make your database as boring as po...
New Tuning Features in Oracle 11g - How to make your database as boring as po...New Tuning Features in Oracle 11g - How to make your database as boring as po...
New Tuning Features in Oracle 11g - How to make your database as boring as po...
 
ggplot2 extensions-ggtree.
ggplot2 extensions-ggtree.ggplot2 extensions-ggtree.
ggplot2 extensions-ggtree.
 
Basic Query Tuning Primer - Pg West 2009
Basic Query Tuning Primer - Pg West 2009Basic Query Tuning Primer - Pg West 2009
Basic Query Tuning Primer - Pg West 2009
 
Clustering com numpy e cython
Clustering com numpy e cythonClustering com numpy e cython
Clustering com numpy e cython
 
Building Real Time Systems on MongoDB Using the Oplog at Stripe
Building Real Time Systems on MongoDB Using the Oplog at StripeBuilding Real Time Systems on MongoDB Using the Oplog at Stripe
Building Real Time Systems on MongoDB Using the Oplog at Stripe
 
Map/reduce, geospatial indexing, and other cool features (Kristina Chodorow)
Map/reduce, geospatial indexing, and other cool features (Kristina Chodorow)Map/reduce, geospatial indexing, and other cool features (Kristina Chodorow)
Map/reduce, geospatial indexing, and other cool features (Kristina Chodorow)
 
Building Real Time Systems on MongoDB Using the Oplog at Stripe
Building Real Time Systems on MongoDB Using the Oplog at StripeBuilding Real Time Systems on MongoDB Using the Oplog at Stripe
Building Real Time Systems on MongoDB Using the Oplog at Stripe
 
The Ring programming language version 1.5.2 book - Part 66 of 181
The Ring programming language version 1.5.2 book - Part 66 of 181The Ring programming language version 1.5.2 book - Part 66 of 181
The Ring programming language version 1.5.2 book - Part 66 of 181
 
Oh Composable World!
Oh Composable World!Oh Composable World!
Oh Composable World!
 
Building Real Time Systems on MongoDB Using the Oplog at Stripe
Building Real Time Systems on MongoDB Using the Oplog at StripeBuilding Real Time Systems on MongoDB Using the Oplog at Stripe
Building Real Time Systems on MongoDB Using the Oplog at Stripe
 
Five
FiveFive
Five
 
Postgres performance for humans
Postgres performance for humansPostgres performance for humans
Postgres performance for humans
 
Palestra sobre Collections com Python
Palestra sobre Collections com PythonPalestra sobre Collections com Python
Palestra sobre Collections com Python
 
Pdxpugday2010 pg90
Pdxpugday2010 pg90Pdxpugday2010 pg90
Pdxpugday2010 pg90
 

Viewers also liked (9)

ATT Case Competition Presentation
ATT Case Competition PresentationATT Case Competition Presentation
ATT Case Competition Presentation
 
выставка
выставкавыставка
выставка
 
UGM
UGMUGM
UGM
 
Fórmula empírica y fórmula molecular
Fórmula empírica y fórmula molecular Fórmula empírica y fórmula molecular
Fórmula empírica y fórmula molecular
 
ORGANIZACION ADMINISTRATIVA
ORGANIZACION ADMINISTRATIVA ORGANIZACION ADMINISTRATIVA
ORGANIZACION ADMINISTRATIVA
 
тренинг мама и я
тренинг мама и ятренинг мама и я
тренинг мама и я
 
Procter & Gamble : Marketing Capabilities
Procter & Gamble : Marketing Capabilities Procter & Gamble : Marketing Capabilities
Procter & Gamble : Marketing Capabilities
 
МКУ ДО ЦДО УКМО проект школьный музей- в каждую школу!
МКУ ДО ЦДО УКМО проект школьный музей- в каждую школу!МКУ ДО ЦДО УКМО проект школьный музей- в каждую школу!
МКУ ДО ЦДО УКМО проект школьный музей- в каждую школу!
 
15.03. спб ярошевич п.с.
15.03. спб ярошевич п.с.15.03. спб ярошевич п.с.
15.03. спб ярошевич п.с.
 

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

Refactoring to Macros with Clojure
Refactoring to Macros with ClojureRefactoring to Macros with Clojure
Refactoring to Macros with Clojure
Dmitry Buzdin
 
JavaScript Advanced - Useful methods to power up your code
JavaScript Advanced - Useful methods to power up your codeJavaScript Advanced - Useful methods to power up your code
JavaScript Advanced - Useful methods to power up your code
Laurence Svekis ✔
 
you need to complete the r code and a singlepage document c.pdf
you need to complete the r code and a singlepage document c.pdfyou need to complete the r code and a singlepage document c.pdf
you need to complete the r code and a singlepage document c.pdf
adnankhan605720
 

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

A Shiny Example-- R
A Shiny Example-- RA Shiny Example-- R
A Shiny Example-- R
 
Refactoring to Macros with Clojure
Refactoring to Macros with ClojureRefactoring to Macros with Clojure
Refactoring to Macros with Clojure
 
ggtimeseries-->ggplot2 extensions
ggtimeseries-->ggplot2 extensions ggtimeseries-->ggplot2 extensions
ggtimeseries-->ggplot2 extensions
 
Emerging Languages: A Tour of the Horizon
Emerging Languages: A Tour of the HorizonEmerging Languages: A Tour of the Horizon
Emerging Languages: A Tour of the Horizon
 
Introduction to R
Introduction to RIntroduction to R
Introduction to R
 
Introduction to Scalding and Monoids
Introduction to Scalding and MonoidsIntroduction to Scalding and Monoids
Introduction to Scalding and Monoids
 
Php my sql - functions - arrays - tutorial - programmerblog.net
Php my sql - functions - arrays - tutorial - programmerblog.netPhp my sql - functions - arrays - tutorial - programmerblog.net
Php my sql - functions - arrays - tutorial - programmerblog.net
 
[Pgday.Seoul 2019] Citus를 이용한 분산 데이터베이스
[Pgday.Seoul 2019] Citus를 이용한 분산 데이터베이스[Pgday.Seoul 2019] Citus를 이용한 분산 데이터베이스
[Pgday.Seoul 2019] Citus를 이용한 분산 데이터베이스
 
R Programming: Export/Output Data In R
R Programming: Export/Output Data In RR Programming: Export/Output Data In R
R Programming: Export/Output Data In R
 
R console
R consoleR console
R console
 
DataMapper
DataMapperDataMapper
DataMapper
 
R meets Hadoop
R meets HadoopR meets Hadoop
R meets Hadoop
 
A Tour of Building Web Applications with R Shiny
A Tour of Building Web Applications with R Shiny A Tour of Building Web Applications with R Shiny
A Tour of Building Web Applications with R Shiny
 
M12 random forest-part01
M12 random forest-part01M12 random forest-part01
M12 random forest-part01
 
Spark + Clojure for Topic Discovery - Zalando Tech Clojure/Conj Talk
Spark + Clojure for Topic Discovery - Zalando Tech Clojure/Conj TalkSpark + Clojure for Topic Discovery - Zalando Tech Clojure/Conj Talk
Spark + Clojure for Topic Discovery - Zalando Tech Clojure/Conj Talk
 
JavaScript Advanced - Useful methods to power up your code
JavaScript Advanced - Useful methods to power up your codeJavaScript Advanced - Useful methods to power up your code
JavaScript Advanced - Useful methods to power up your code
 
Advanced Data Visualization in R- Somes Examples.
Advanced Data Visualization in R- Somes Examples.Advanced Data Visualization in R- Somes Examples.
Advanced Data Visualization in R- Somes Examples.
 
PhpUnit - The most unknown Parts
PhpUnit - The most unknown PartsPhpUnit - The most unknown Parts
PhpUnit - The most unknown Parts
 
R code
R codeR code
R code
 
you need to complete the r code and a singlepage document c.pdf
you need to complete the r code and a singlepage document c.pdfyou need to complete the r code and a singlepage document c.pdf
you need to complete the r code and a singlepage document c.pdf
 

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

  • 1. 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
  • 2. 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")
  • 3. 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") {
  • 4. 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] }
  • 5. ) # ------------------------- 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("NULLn") paste0("x=", round(e$x, 4), " y=", round(e$y, 4), "n") } xy_range_str <- function(e) { if(is.null(e)) return("NULLn") 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) )
  • 6. }) # 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("NULLn") paste0("x=", round(e$x, 4), " y=", round(e$y, 4), "n") } xy_range_str <- function(e) { if(is.null(e)) return("NULLn") 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("NULLn") paste0("x=", round(e$x, 4), " y=", round(e$y, 4), "n") } xy_range_str <- function(e) { if(is.null(e)) return("NULLn") paste0(" xmin=", round(e$xmin, 4), " xmax=", round(e$xmax, 4), " ymin=", round(e$ymin, 4), " ymax=", round(e$ymax, 4))
  • 7. } 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({
  • 8. 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)
  • 9. 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) } )