I am working on my first shiny app, trying to build a random forest regression to predict the arrest charge for a Crime Dataset. I got an error said object offense_category not found when running the app. I have tried many suggestions online but it's still not working.
Here is my current ui.R code:
ui <- fluidPage(theme = shinytheme("united"),
#header
headerPanel("Prediction"),
#inputs
sidebarPanel(
h2("Filter"),
selectizeInput("offense_category", label="Offense Category", choices=c("", sort(unique(df$offense_category))),multiple=FALSE),
radioButtons(
"year",
"Select year",
choices = c("2020", "2021","2022","2023"),
selected = "2020"
),
selectizeInput("neighborhood", label="Neighborhood", choices=c("", sort(unique(df$neighborhood))),multiple=FALSE),
actionButton("predictbutton", "Predict", class = "btn btn-primary")
),
mainPanel(h2("Prediction"),
tableOutput(outputId = 'chargeprediction'))
)
And my server.R code:
server <- function(input, output){
#input data
datainput <- reactive({
result <- data.frame(
Name = c("Offense Category",
"Year",
"Neighborhood"),
Value = as.character(c(input$offense_category,
input$year,
input$neighborhood)),
stringsAsFactors=FALSE)
Estimate_charge <- 0
result <- rbind(result, Estimate_charge)
write.table(result, "result.csv", sep="", quote=FALSE, row.names=FALSE, col.names=FALSE)
test <- read.csv(paste("result",".csv",sep=""),header=TRUE)
Output <- data.frame(Prediction=predict(rf,test), round(predict(rf,test,type="prob"),1))
print(Output)
})
output$chargeprediction <- renderTable({
if (input$predictbutton > 0){
isolate(datainput())
}
})
}
And here is the error in console for your reference:
If the code runs properly, it should output a table containing the predicted result, and the corresponding probability of that prediction.
Random Forest model:
rf <- randomForest(charge ~ offense_category+year+neighborhood, data=trainingset, ntree=500, importance=TRUE)

