June 26, 2018
Crime is something that many governments wish to curtail. As such, it is important to understand the relationships between difference variables to see how they might co-occur.
The Shiny app allows the user to select 2 variables. Behind the scenes, the server runs a linear regression model on the 2 variables. The plot will display the fitted line with the raw data.
Please see this link for the App: https://assignments.shinyapps.io/Week4/
The US Arrests dataset comes in built to R. It is captured at a state level and and contains the following variables:
Beginning with exploratory analysis on the US Arrests dataset
library(shiny)
shinyUI(fluidPage(
titlePanel("US Arrests: understanding the relationships between variables"),
sidebarLayout(
sidebarPanel(
h4("Select Variables"),
selectInput('ycol', 'Y Variable', names(USArrests),
selected=names(USArrests)[[2]]),
selectInput('xcol', 'X Variable', names(USArrests))),
mainPanel(
h3("Scatter Plot and Linear Model", align = "center"),
plotOutput("distPlot")))
))
<!–html_preserve–>
shinyServer(function(input, output, session) {
selectedData <- reactive({
USArrests[, c(input$xcol, input$ycol)]
})
model <- reactive({
dat <- selectedData()
model <- lm(dat[,2]~dat[,1], data = dat)
return(model)
})
output$distPlot <- renderPlot({
plot(selectedData(), xlab = "X Var", ylab = "Y Var")
abline(model(), col = "red")
mtext(paste('y =', round(coef(model())[[2]],1), '* x', '+', round(coef(model())[[1]],1)))
})
})