Enable/disable selectInput based on value in another selectInput - shiny

In my shiny app, I need to disable selectInput Season and selectInput Mesh if the value selected for selectInput Species is "Kemps". Those same two selectInput objects should be enabled for any other species selection. I found some shinyjs code (https://towardsdatascience.com/heres-how-to-spice-up-your-shiny-app-84866ccb69dd) and adapted to my app but I am getting errors. I would appreciate any guidance. Thanks!
spp <- c("Atlantic Sturgeon","Green","Kemps")
seas <- c("Fall","Winter","Spring","Summer")
mus <- c("A","B","C","D","D1","D2","E")
meshes <- c("Large","Small")
ui <- fluidPage(
titlePanel(title=div(img(src="imgPS.png",height=75),"Protected Species Model")),
sidebarLayout(
sidebarPanel(
selectInput("species", "Protected Species", spp),
selectInput("Season", "Season", seas),
selectInput("MU", "Management Unit", mus),
selectInput("Mesh", "Mesh Size", meshes),
numericInput("trip", "n Trips", 1, min = 1),
actionButton("btnEstTakes","Estimate Takes")
),
mainPanel(
h2("Predicted Takes"),
textOutput("prediction_text")
)
)
)
server <- function(input, output, session) {
observeEvent(input$species, {
if(input$species == "Kemps"){
shinyjs::disable(id = "Season")
shinyjs::disable(id = "Mesh")
}
else {
shinyjs::enable(id = "Season")
shinyjs::enable(id = "Mesh")
}
predict_df <- eventReactive(input$btnEstTakes, {
# Validate the user input. I dont trust these people! :)
validate(need(input$species, "Please select a valid Species!"))
validate(need(input$Season, "Please select a Season!"))
validate(need(input$MU, "Please select a Management Unit!"))
validate(need(input$Mesh, "Please select a Mesh Size!"))
validate(need(input$trip > 0, "Enter a valid trip count!"))
validate(need(input$species != "Atlantic Sturgeon" | (input$MU != "D1" & input$MU != "D2"),
"Management Unit selection not valid for Atlantic Sturgeon"))
validate(need(input$species != "Green" | input$MU != "D",
"Management Unit selection not valid for Green"))
validate(need(input$species != "Kemps" | (input$MU != "D" & input$MU != "D1"),
"Management Unit selection not valid for Kemps"))
ITPYear <- c(2013,2014,2015,2016,2017,2018,2019,2020,2021)
Species <- input$species
Season <- input$Season
MU <- input$MU
Mesh <- input$Mesh
LogEffort <- log(input$trip)
# Create data set for Kemps
df1 <- cbind(MU,LogEffort)
df1 <- as.data.frame(df1)
df1$Species <- Species
df1$MU <- as.factor(df1$MU)
df1$LogEffort <- as.double(df1$LogEffort)
# Create data set for Atlantic Sturgeon and Green
df2 <- cbind(Season,MU,Mesh,LogEffort)
df2 <- as.data.frame(df2)
df2 <- df2[rep(1,9),]
df2 <- cbind(ITPYear,df2)
df2$Species <- Species
df2$ITPYear <- as.factor(df2$ITPYear)
df2$Season <- as.factor(df2$Season)
df2$MU <- as.factor(df2$MU)
df2$Mesh <- as.factor(df2$Mesh)
df2$LogEffort <- as.double(df2$LogEffort)
df3 <- df2
df4 <- cbind(Species,Season,MU,Mesh,LogEffort)
df4 <- as.data.frame(df4)
# Predict based on species selection
if(Species=="Kemps"){
df1$Prediction <- predict(mod.kemps,type="response", newdata=df1)
df1$Live <- round(df1$Prediction * (1-kemps.dead), 0)
df1$Dead <- round(df1$Prediction * (kemps.dead), 0)
} else if(Species=="Green") {
df2$Prediction <- predict(mod.green,type="response",newdata=df2)
pred.use <- mean(df2$Prediction)
df4$Live <- round(pred.use * (1-green.dead), 0)
df4$Dead <- round(pred.use * (green.dead), 0)
} else {
df3$Prediction <- predict(mod.astg,type="response",newdata=df3)
pred.use <- mean(df3$Prediction)
df4$Live <- round(pred.use * (1-astg.dead), 0)
df4$Dead <- round(pred.use * (astg.dead), 0)
}
df.pick <- cbind(Species,Season,MU,Mesh)
df.pick <- as.data.frame(df.pick)
if(Species=="Kemps"){
df.pick$Live <- df1$Live
df.pick$Dead <- df1$Dead
} else {
df.pick$Live <- df4$Live
df.pick$Dead <- df4$Dead
}
df.use <- df.pick[,c('Species','Live', 'Dead')]
return(df.use)
})
df <- reactive({
predict_df()
})
output$prediction_text <- renderText({
paste0("The model predicted ", df()$Live, " live ", df()$Species, " and ", df()$Dead, " dead ", " ", df()$Species, ".")
})
}
shinyApp(ui, server)

Your code works fine if you enable {shinyjs} at beginning of ui:
ui <- fluidPage(
shinyjs::useShinyjs(),
...
(also close with }) the observeEvent)
observeEvent(input$species, {
if(input$species == "Kemps"){
shinyjs::disable(id = "Season")
shinyjs::disable(id = "Mesh")
}
else {
shinyjs::enable(id = "Season")
shinyjs::enable(id = "Mesh")
}
})

Related

R Shiny problem with inputs belonging to a bsCollapsePanel

In this shiny App (code below), tabPanel 'Scatter plot', note that the plot is correctly rendered only when the user expand the bsCollapsePanel 'Marker settings' for the first time. Before expanding the panel 'Marker settings' at first time, the message Error: argument is of length zero is shown. Can someone find out where the error is in the code?
library(shiny)
library(shinyBS)
library(tidyverse)
shinyApp(
ui = fluidPage(
tabsetPanel(
tabPanel("mtcars",
dataTableOutput("mtcarsDATA")),
tabPanel("Scatter plot",
sidebarPanel(
bsCollapse(id = "Side panel", open = "Variables",
bsCollapsePanel("Variables",
uiOutput("varx"),
uiOutput("vary"))
)
),
mainPanel(
bsCollapsePanel("Marker settings",
uiOutput("showMrk"),
uiOutput("shpMrk"),
uiOutput("forPorForma"),
uiOutput("forPorVar"),
uiOutput("mrkTrsp")),
plotOutput('SctPlot'))
)
)
),
server <- function(input, output) {
output$mtcarsDATA <- renderDataTable({
data <- mtcars
getModel <- reactive({
names(data) })
output$varx <- renderUI({
selectInput("varsel.x", HTML("Select var X<span style='color: red'>*</span>"),
choices = as.list(getModel()), multiple = F) })
getModelnum <- reactive({
filterNumeric <- data[sapply(data, is.numeric)]
names(filterNumeric) })
output$vary <- renderUI({
selectInput("varsel.y", HTML("Select var Y<span style='color: red'>*</span>(numerical only)"),
choices = as.list(getModelnum()), multiple = F) })
output$showMrk <- renderUI({
checkboxInput("show_Mrk", "Show marker", value=T) })
output$shpMrk <- renderUI({
conditionalPanel(condition = "input.show_Mrk == T",
radioButtons("shp_Mrk", "Format marker",
choices = c("by shape", "by variable"))) })
output$forPorForma <- renderUI({
conditionalPanel(condition = "input.shp_Mrk == 'by shape' & input.show_Mrk == T",
sliderInput("for_PorForma", 'Deslize para mudar o formato do marcador',
min = 1, max=25, value = 16)) })
output$mrkTrsp <- renderUI({
conditionalPanel(condition = "input.show_Mrk == T",
sliderInput("mrk_Trsp", 'Slide to change marker transparency',
min = 0, max=1, value = .5, step=.05)) })
getModelcat <- reactive({
filterCaracter <- data[sapply(data, is.character)]
names(filterCaracter) })
output$forPorVar <- renderUI({
conditionalPanel(condition = "input.show_Mrk == 1 & input.shp_Mrk == 'by variable'",
selectInput("forPorVar.sel", "Select var",
choices = as.list(getModelcat()), multiple = F)) })
output$SctPlot <- renderPlot({
if(input$show_Mrk == T){
if(input$shp_Mrk == "by shape") {
geomPoint <- geom_point(alpha=1-input$mrk_Trsp, shape=input$for_PorForma) } else {
geomPoint <- geom_point(alpha=1-input$mrk_Trsp, aes_string(shape=(input$forPorVar.sel))) }} else {
geomPoint <- geom_point(alpha=0) }
p <- data %>%
ggplot(aes_string(x=input$varsel.x, y=input$varsel.y)) +
geomPoint
p
})
data
})
}
)

How to use the Undo button in R shiny to undo earlier operations and recover them

I am working on a R shiny app that reads CSV and produces a dataTable. I am looking for a way to undo prior actions one by one whenever I clik the Undo button (like CTRL+ Z in Windows), however, the code below restores all previous actions once I press the Undo button.
Could someone please assist me in resolving this problem?
csv data
ID Type Range
21 A1 B1 100
22 C1 D1 200
23 E1 F1 300
app.R
library(shiny)
library(reshape2)
library(DT)
library(tibble)
###function for deleting the rows
splitColumn <- function(data, column_name) {
newColNames <- c("Unmerged_type1", "Unmerged_type2")
newCols <- colsplit(data[[column_name]], " ", newColNames)
after_merge <- cbind(data, newCols)
after_merge[[column_name]] <- NULL
after_merge
}
###_______________________________________________
### function for inserting a new column
fillvalues <- function(data, values, columName){
df_fill <- data
vec <- strsplit(values, ",")[[1]]
df_fill <- tibble::add_column(df_fill, newcolumn = vec, .after = columName)
df_fill
}
##function for removing the colum
removecolumn <- function(df, nameofthecolumn){
df[ , -which(names(df) %in% nameofthecolumn)]
}
### use a_splitme.csv for testing this program
ui <- fluidPage(
sidebarLayout(
sidebarPanel(
fileInput("file1", "Choose CSV File", accept = ".csv"),
checkboxInput("header", "Header", TRUE),
actionButton("Splitcolumn", "SplitColumn"),
uiOutput("selectUI"),
actionButton("deleteRows", "Delete Rows"),
textInput("textbox", label="Input the value to replace:"),
actionButton("replacevalues", label = 'Replace values'),
actionButton("removecolumn", "Remove Column"),
actionButton("Undo", 'Undo')
),
mainPanel(
DTOutput("table1")
)
)
)
server <- function(session, input, output) {
rv <- reactiveValues(data = NULL, orig=NULL)
observeEvent(input$file1, {
file <- input$file1
ext <- tools::file_ext(file$datapath)
req(file)
validate(need(ext == "csv", "Please upload a csv file"))
rv$orig <- read.csv(file$datapath, header = input$header)
rv$data <- rv$orig
})
output$selectUI<-renderUI({
req(rv$data)
selectInput(inputId='selectcolumn', label='select column', choices = names(rv$data))
})
observeEvent(input$Splitcolumn, {
rv$data <- splitColumn(rv$data, input$selectcolumn)
})
observeEvent(input$deleteRows,{
if (!is.null(input$table1_rows_selected)) {
rv$data <- rv$data[-as.numeric(input$table1_rows_selected),]
}
})
output$table1 <- renderDT({
rv$data
})
observeEvent(input$replacevalues, {
rv$data <- fillvalues(rv$data, input$textbox, input$selectcolumn)
})
observeEvent(input$removecolumn, {
rv$data <- removecolumn(rv$data,input$selectcolumn)
})
observeEvent(input$Undo, {
rv$data <- rv$orig
})
}
We can create a list to host every instance of the table to recover multiple undo's. Note that if the .csv is very big this approach will become inefficient very quick. We can mitigate this infefficiency by implementing a button that clears the undo list up to a point or implementing an append function that saves only the part modified of the table rather than the whole table.
Please, fill free to modify the answer or use it for another answer.
library(shiny)
library(reshape2)
library(DT)
library(tibble)
###function for deleting the rows
splitColumn <- function(data, column_name) {
newColNames <- c("Unmerged_type1", "Unmerged_type2")
newCols <- colsplit(data[[column_name]], " ", newColNames)
after_merge <- cbind(data, newCols)
after_merge[[column_name]] <- NULL
after_merge
}
###_______________________________________________
### function for inserting a new column
fillvalues <- function(data, values, columName){
df_fill <- data
vec <- strsplit(values, ",")[[1]]
tibble::add_column(df_fill, newcolumn = vec, .after = columName)
}
##function for removing the colum
removecolumn <- function(df, nameofthecolumn){
df[ , -which(names(df) %in% nameofthecolumn)]
}
# APP ---------------------------------------------------------------------
ui <- fluidPage(
sidebarLayout(
sidebarPanel(
fileInput("file1", "Choose CSV File", accept = ".csv"),
checkboxInput("header", "Header", TRUE),
actionButton("Splitcolumn", "SplitColumn"),
uiOutput("selectUI"),
actionButton("deleteRows", "Delete Rows"),
textInput("textbox", label = "Input the value to replace:"),
actionButton("replacevalues", label = 'Replace values'),
actionButton("removecolumn", "Remove Column"),
actionButton("Undo", 'Undo')
),
mainPanel(
DTOutput("table1")
)
)
)
server <- function(session, input, output) {
#added undo (a list) and counter to accumulate more than one undo
rv <- reactiveValues(data = NULL, orig=NULL, undo = list(), counter = 1)
# csv file ----------------------------------------------------------------
observeEvent(input$file1, {
file <- input$file1
ext <- tools::file_ext(file$datapath)
req(file)
validate(need(ext == "csv", "Please upload a csv file"))
rv$orig <- read.csv(file$datapath, header = input$header)
rv$data <- rv$orig
})
output$selectUI <- renderUI({
req(rv$data)
selectInput(inputId='selectcolumn', label='select column', choices = names(rv$data))
})
# rest of the app ---------------------------------------------------------
observeEvent(input$Splitcolumn, {
rv$undo[[rv$counter]] <- rv$data
rv$counter <- rv$counter + 1
rv$data <- splitColumn(rv$data, input$selectcolumn)
})
observeEvent(input$deleteRows,{
if (!is.null(input$table1_rows_selected)) {
rv$undo[[rv$counter]] <- rv$data
rv$counter <- rv$counter + 1
rv$data <- rv$data[-as.numeric(input$table1_rows_selected),]
}
})
output$table1 <- renderDT({
rv$data
})
observeEvent(input$replacevalues, {
rv$undo[[rv$counter]] <- rv$data
rv$counter <- rv$counter + 1
rv$data <- fillvalues(rv$data, input$textbox, input$selectcolumn)
})
observeEvent(input$removecolumn, {
rv$undo[[rv$counter]] <- rv$data
rv$counter <- rv$counter + 1
rv$data <- removecolumn(rv$data,input$selectcolumn)
})
observeEvent(input$Undo, {
if (rv$counter > 1) {
rv$data <- rv$undo[[rv$counter - 1]]
#index must be more than 1
rv$counter <- rv$counter - 1
}
})
}
shinyApp(ui, server)

Update dataframe to change leaflet output based on users choice in shiny

I'm new to shiny and I have tried multiple ways to update the leaflet output based on two selectinput, the first chooses the data frame to use and the second what to filter on. this bit is working but I don't seem to be able to pass this to the leaflet proxy, any thoughts would be appreciated
poldat <- vroom::vroom("F:/ming1/data/poldat.csv")
meddat <- vroom::vroom("F:/ming1/data/meddat.csv")
medlist <- vroom::vroom("F:/ming1/data/ddl1.csv")
pollist <- vroom::vroom("F:/ming1/data/ddl2.csv")
library(shiny)
library(leaflet)
library(RColorBrewer)
library(vroom)
ui <- bootstrapPage(
tags$style(type = "text/css", "html, body {width:100%;height:100%}"),
leafletOutput("map", width = "50%", height = "100%"),
absolutePanel(top = 10, right = 10,
selectInput('var1', 'Select the area you wish to view', choices = c("choose" = "","police","Medical")),
selectInput('var2', 'Select the area you would like to view' ,choices =c("choose" = "")),
))
server <- function(input, output, session){
output$map <- renderLeaflet({
leaflet(map1) %>% addTiles() %>%
fitBounds(~min(long), ~min(lat), ~max(long), ~max(lat))
})
observe({
a_option <- input$var1
if (a_option == "police") {
updateSelectInput(session, "var2", choices = c("choose" = "",pollist$row1))
}else{
updateSelectInput(session, "var2", choices = c("choose" = "",medlist$row1))
}
})
observe({
catreq <- input$var1
#mapfilt <- input$var2
mydf<- input$var1
if (mydf == "police") {
mydf = poldat
}else{
mydf = meddat
}
mycol <- input$var1
if (mycol == "police") {
mycol = "fallswithin"
}else{
mycol = "healtharea"
}
map1 <- subset(mydf, mycol == input$var2)
leafletProxy("map", data = map1[2:3]) %>% addTiles()# %>%
addMarkers(clusterOptions = markerClusterOptions(),label = paste("test"))
})
}
shinyApp(ui, server)

Detecting arrow key (cursor key) in Shiny

I would like to link an action to the arrow/cursor keys in my Shiny app.
The action is already linked to pressing previous and next buttons. So I would like to add the eventExpr "cursor right" and "cursor left" to it, respectively. This is to plot one plot after another. Here is a simplified example with mtcars dataset.
datasets <- list(mtcars, iris, PlantGrowth)
ui <- fluidPage(
mainPanel(
titlePanel("Simplified example"),
tableOutput("cars"),
actionButton("prevBtn", icon = icon("arrow-left"), ""),
actionButton("nextBtn", icon = icon("arrow-right"), ""),
verbatimTextOutput("rows")
)
)
server <- function(input, output) {
output$cars <- renderTable({
head(dat())
})
dat <- reactive({
if (is.null(rv$nr)) {
d <- mtcars
}
else{
d <- datasets[[rv$nr]]
}
})
rv <- reactiveValues(nr = 1)
set_nr <- function(direction) {
rv$nr <- rv$nr + direction
}
observeEvent(input$nextBtn, { # here I would like add the sec. eventExpr.
set_nr(1)
})
observeEvent(input$prevBtn, { # here I would like add the sec. eventExpr.
set_nr(-1)
})
ro <- reactive({
nrow(dat())
})
output$rows <- renderPrint({
print(paste(as.character(ro()), "rows"))
})
vals <- reactiveValues(needThisForLater = reactive(30 * ro()))
}
shinyApp(ui = ui, server = server)```
You can attach a keydown event handler to the document:
datasets <- list(mtcars, iris, PlantGrowth)
js <- paste(
"$(document).on('keydown', function(event){",
" var key = event.which;",
" if(key === 37){",
" Shiny.setInputValue('arrowLeft', true, {priority: 'event'});",
" } else if(key === 39){",
" Shiny.setInputValue('arrowRight', true, {priority: 'event'});",
" }",
"});"
)
ui <- fluidPage(
tags$head(tags$script(HTML(js))),
mainPanel(
titlePanel("Simplified example"),
tableOutput("cars"),
actionButton("prevBtn", icon = icon("arrow-left"), ""),
actionButton("nextBtn", icon = icon("arrow-right"), ""),
verbatimTextOutput("rows")
)
)
server <- function(input, output) {
output$cars <- renderTable({
head(dat())
})
dat <- reactive({
if (is.null(rv$nr)) {
d <- mtcars
}
else{
d <- datasets[[rv$nr]]
}
})
rv <- reactiveValues(nr = 1)
set_nr <- function(direction) {
rv$nr <- rv$nr + direction
}
observeEvent(list(input$nextBtn, input$arrowRight), {
set_nr(1)
})
observeEvent(list(input$prevBtn, input$arrowLeft), {
set_nr(-1)
})
ro <- reactive({
nrow(dat())
})
output$rows <- renderPrint({
print(paste(as.character(ro()), "rows"))
})
vals <- reactiveValues(needThisForLater = reactive(30 * ro()))
}
shinyApp(ui = ui, server = server)

Input 2nd file in R Shiny only if results from 1st Input file satisfies requirement

I am relatively new on using R Shiny, I am trying to build Shiny app for predictive modeling.
I have R code ready with me and have loaded them in R Shiny.
Please refer to below ui.r and server.r which I have prepared.
shinyUI(
fluidPage(
titlePanel("Prediction"),
sidebarLayout(
sidebarPanel(
fileInput('file1', 'Choose Past CSV File',
accept=c('text/csv',
'text/comma-separated-values,text/plain',
'.csv')),
conditionalPanel(
condition = "output.fileUploaded",
fileInput('file2', 'Choose Future CSV File',
accept=c('text/csv',
'text/comma-separated-values,text/plain',
'.csv')),
downloadButton("downloadData", "Download Prediction")
)
),
mainPanel(
tabsetPanel(type = "tabs",
tabPanel('Results', (DT::dataTableOutput('table'))),
tabPanel("Model Summary",
verbatimTextOutput("summary"))
)
)
)
)
)
shinyServer(function(input, output) {
# hide the output
output$fileUploaded <- reactive({
return(!is.null(input$file1))
})
outputOptions(output, 'fileUploaded', suspendWhenHidden=FALSE)
data <- reactive({
File <- input$file1
if (is.null(File))
return(NULL)
complete <- read.csv(File$datapath,header=T,na.strings=c(""))
File1 <- input$file2
if (is.null(File1))
return(NULL)
raw.data <- read.csv(File1$datapath,header=T,na.strings=c(""))
#Change all variable to factor
complete[] <- lapply(complete, factor)
complete$Target <- recode(complete$Target," 'YES' = 1; 'Yes' = 1; 'NO' = 0 " )
set.seed(33)
splitIndex <- createDataPartition(complete$Target, p = .75, list = FALSE, times = 1)
trainData <- complete[ splitIndex,]
testData <- complete[-splitIndex,]
fitControl <- trainControl(method = "repeatedcv", number = 4, repeats = 4)
set.seed(33)
gbmFit1 <- train(as.factor(Target) ~ ., data = trainData, method = "gbm", trControl = fitControl,verbose = FALSE)
pred <- predict(gbmFit1, testData,type= "prob")[,2]
perf = prediction(pred, testData$Target)
pred1 = performance(perf, "tpr","fpr")
acc.perf <- performance(perf, "acc")
ind = which.max( slot(acc.perf, "y.values")[[1]])
acc = slot(acc.perf, "y.values")[[1]][ind]
output$summary <- renderPrint({
print(c(Accuracy=acc))
})
raw.data[] <- lapply(raw.data, factor)
testpred <- predict(gbmFit1, raw.data,type= "prob")[,2]
final = cbind(raw.data, testpred)
final
})
output$table = DT::renderDataTable({
final <- data()
DT::datatable(
data(), options = list(
pageLength = 5)
)
})
output$downloadData <- downloadHandler(
filename = function() { paste('SLA Prediction', '.csv', sep='') },
content = function(file) {
write.csv(data(),file)
}
)
return(output)
})
Model is created using first Input file, my requirement is user should asked to upload 2nd input file (for which they want to predict results) only if model Accuracy which calculated using first input file stored in variable acc should be more than 0.9, I am not able to get solution for this, can anyone help me in this.
Now the second file input depends on the variable acc and shows up only when it is bigger than 0.9. I additionally did some changes, mainly because your code didn't work on my laptop :). Instead of return(NULL) you can use the function req to ensure that the values are available.
library(shiny)
library(shinysky)
library(shinythemes)
library(caret)
library(gbm)
library(ROCR)
library(car)
ui <- shinyUI(
fluidPage(
theme = shinytheme("united"), # added new theme from the package 'shinythemes'
titlePanel("Prediction"),
sidebarLayout(
sidebarPanel(
fileInput('file1', 'Choose Past CSV File',
accept=c('text/csv',
'text/comma-separated-values,text/plain',
'.csv')),
uiOutput("dynamic")
),
mainPanel(
# added busyIndicator
busyIndicator(text = "Calculation in progress..",
img = "shinysky/busyIndicator/ajaxloaderq.gif", wait = 500),
tabsetPanel(type = "tabs",
tabPanel('Results',
(DT::dataTableOutput('table'))),
tabPanel("Model Summary",
verbatimTextOutput("summary")),
tabPanel("Predictions",
DT::dataTableOutput('tablePred'))
)
)
)
)
)
server <- shinyServer(function(input, output) {
# hide the output
output$fileUploaded <- reactive({
return(!is.null(input$file1))
})
outputOptions(output, 'fileUploaded', suspendWhenHidden=FALSE)
data <- reactive({
File <- input$file1
req(File)
complete <- read.csv(File$datapath,header=T,na.strings=c(""))
complete
})
model <- reactive({
complete <- lapply(data(), factor)
complete$Target <- recode(data()$Target," 'YES' = 1; 'Yes' = 1; 'NO' = 0 " )
set.seed(33)
splitIndex <- createDataPartition(data()$Target, p = .75, list = FALSE, times = 1)
trainData <- data()[ splitIndex,]
testData <- data()[-splitIndex,]
fitControl <- trainControl(method = "repeatedcv", number = 4, repeats = 4)
set.seed(33)
gbmFit1 <- train(as.factor(Target) ~ ., data = trainData, method = "gbm", trControl = fitControl,verbose = FALSE)
pred <- predict(gbmFit1, testData, type= "prob")[,2]
perf = prediction(pred, testData$Target)
pred1 = performance(perf, "tpr","fpr")
acc.perf <- performance(perf, "acc")
ind = which.max( slot(acc.perf, "y.values")[[1]])
acc = slot(acc.perf, "y.values")[[1]][ind]
retval <- list(model = gbmFit1, accuracy = acc)
return(retval)
})
output$summary <- renderPrint({
req(model())
print(model())
})
output$dynamic <- renderUI({
req(model())
if (model()$accuracy >= 0.9)
list(
fileInput('file2', 'Choose Future CSV File',
accept=c('text/csv',
'text/comma-separated-values,text/plain',
'.csv')),
downloadButton("downloadData", "Download Prediction")
)
})
data2 <- reactive({
req(input$file2)
File1 <- input$file2
raw.data <- read.csv(File1$datapath,header=T,na.strings=c(""))
raw.data
})
preds <- reactive({
raw.data <- data2()
testpred <- predict(model()$model, raw.data,type= "prob")[,2]
print(testpred)
final = cbind(raw.data, testpred)
final
})
output$table = DT::renderDataTable({
DT::datatable(data(), options = list(pageLength = 15))
})
output$tablePred = DT::renderDataTable({
req(input$file2)
DT::datatable(preds(), options = list(pageLength = 15))
})
output$downloadData <- downloadHandler(
filename = function() { paste('SLA Prediction', '.csv', sep='') },
content = function(file) {
write.csv(preds(),file)
}
)
return(output)
})
shinyApp(ui, server)