I need to only display a BS modal when a button is pressed and and a condition on a variable is met.
This is a simple app that demonstrates what the challenge is. I need to display a BS modal when num_rows >= 500, and the submit button is fired, not just when the submit button is fired.
I am aware this could be done with a conditionalPanel using input.slider as one of the conditions, but in my real project it is much more complicated than this, and the BS modal/conditional panel needs to depend on both a button (user input) and a variable assigned in the server.
library(shiny)
library(shinyBS)
data = matrix(rnorm(1000*10, 0, 1), nrow = 1000)
ui <- fluidPage(
fluidRow(
column(width = 4,
sliderInput("slider", "Choose Number of Rows to Display", 0, 1000, value = NULL),
submitButton('Submit'),
bsModal("modalExample", "Yes/No", "submit", size = "small", wellPanel(
p(div(HTML("<strong>Warning: </strong> you have chosen to display a large
number of rows. Are you sure you want to proceed?"))),
actionButton("no_button", "Yes"),
actionButton("yes_button", "No")
))
),
column(width = 8,
tableOutput('data')
)
)
)
server <- shinyServer(function(input, output, server){
observe({
num_rows <- input$slider
if(num_rows >= 500){
#
# ACTIVATE MODAL PANEL
#
observeEvent(input$no_button, {
# Do not show table
})
observeEvent(input$yes_button, {
output$table <- renderTable(data)
})
} else{ # Display table normally if number of rows is less than 500
output$table <- renderTable(data)
}
})
})
shinyApp(ui, server)
Have a look at the following code. I disabled the action button if num_rows<500 with the package shinyjs. If num_rows>=500 the action button becomes available to trigger the popup. To update the number of rows selected with the slider you'll have to press the submit button every time. Hope this helps or gets you some ideas. For now I have not implemented your warning message (that did not work for me). Another issue: the slider and display for the pop up only work towards increasing number of rows, not decreasing afterwards. If you find a solution for that, pls share =)
library(shiny)
library(shinyBS)
library(shinyjs)
data = matrix(rnorm(1000*10, 0, 1), nrow = 1000)
data1=data[(1:500),]
head(data)
ui <- fluidPage(
fluidRow(
column(width = 4,
sliderInput("slider", "Choose Number of Rows to Display", 0, 1000, value = NULL),
submitButton('Submit'),
actionButton('Show','Show'),
useShinyjs(),
bsModal("modalExample",'Yes/No','Show', size = "large",tableOutput("tab")
# wellPanel(
# p(div(HTML("<strong>Warning: </strong> you have chosen to display a large
# number of rows. Are you sure you want to proceed?")
# )))
)),
column(width = 8,tableOutput('table'))))
server <- function(input, output)({
observe({
num_rows = input$slider
if(num_rows<500 &num_rows!=0) {
shinyjs::disable('Show')
output$table <- renderTable({
data = data1[(1:num_rows),]
print(head(data1))
data})
}else{
shinyjs::enable('Show')
output$tab = renderTable({
data = data[(1:num_rows),]
data}) }
})
})
shinyApp(ui, server)
Related
I have an app which creates boxes. Each box has a button that triggers a modal. The modal has inputs which the user changes and then a button which triggers an action based on those inputs (basically just uploading to a database). Because each box has a different specification, I wrote a module and then loop thru a list, creating a box for each element. This works fine.
However, the flow in the modal and observeEvent has a flaw: the first run thru I get the desired results, but on the second occasion in the same box (same id module), after pressing the modal button to update, it will not use the new inputs, but rather what happened in the first run. I am guessing it has something to do with the namespace/observeEvent combination as I might be triggering the event with a "stored" namespace? Would I need to somehow "flush" the namespace after every update? Anyway, any help appreciated as it gets confusing fast with all the namespace/modules combinations.
library(shiny)
library(shinyWidgets)
ui <- navbarPage(
'page', collapsible = TRUE,
tabPanel("test",
useSweetAlert(),
sidebarLayout(
sidebarPanel(),
mainPanel(
uiOutput('all_products_ui')
)
)
)) # end navbar
server <- shinyServer(function(input, output) {
list_products <- c(1,2,3,4,5)
# Now, I will create a UI for all the products
output$all_products_ui <- renderUI({
r <- tagList()
progress_move <- 0
for(k in 1:length( list_products )){
r[[k]] <- ExistingProductUI(id = k, product = list_products[[k]] )
}
r
})
# handlers duplicate a call to module depending on the id of ExistingProductUI
handlers <- list()
observe(
handlers <<- lapply(seq.int(length( list_products )),
function(i) {
callModule(ExistingProductUpdate,
id = i,
product = list_products[[i]] )
})
)
handlers
}) # end of server ----
# UI module ------------------------------------------------------
ExistingProductUI <- function(id, product){
ns <- NS(id)
box(title = as.character(p$title),
product["title"],
footer = tagList(
actionBttn(
inputId = ns("change_selected"), label = "change"),
)
)
}
# server module ------------------------------------------------------
ExistingProductUpdate <- function(input, output, session, product){
ns <- session$ns
observeEvent(input$change_selected, {
# when box button is clicked for this product (id)
# FIRST: show a modal
showModal(
modalDialog(
title = "what do you want to change?",
tagList(
radioGroupButtons(inputId = ns("change_selected_choice"), labels = "change x", choices = c(1,2,3,4)),
sliderInput(ns("change_selected_pct"), "change y:", min = -50, max = 100, value = 0, step = 5)
),
easyClose = TRUE,
footer = tagList(
actionButton(ns("change_selected_submit"), "submit!", icon = icon("check")),
modalButton("never mind")
)
)
)
# SECOND: when change_selected_submit is clicked,
observeEvent(input$change_selected_submit, {
# do some calculations with product using what I inputed in modal ---
# then, update a table ----
functionToUploadThings(product, input$change_selected_choice)
# THIRD: Close with a confirmation
sendSweetAlert(
session,
title = "Success!",
type = "success",
btn_labels = "Ok",
closeOnClickOutside = TRUE,
width = NULL
)
})
})
}
Below is a solution that works. The problem was that you nested your observeEvent in the module. I'm not entirely sure why this led to problems, some values weren't processed correctly. However, you don't need to nest the observeEvent, the second one gets also triggered by the actionButton in the modal when it is by its own. Additionally, I included a removeModal before the success notification is shown:
library(shiny)
library(shinyWidgets)
library(shinydashboard)
ui <- navbarPage(
'page', collapsible = TRUE,
tabPanel("test",
useSweetAlert(),
sidebarLayout(
sidebarPanel(),
mainPanel(
uiOutput('all_products_ui')
)
)
)) # end navbar
server <- shinyServer(function(input, output) {
list_products <- c(1,2,3,4,5)
# Now, I will create a UI for all the products
output$all_products_ui <- renderUI({
r <- tagList()
progress_move <- 0
for(k in 1:length( list_products )){
r[[k]] <- ExistingProductUI(id = k, product = list_products[[k]] )
}
r
})
# handlers duplicate a call to module depending on the id of ExistingProductUI
handlers <- list()
observe(
handlers <<- lapply(seq.int(length( list_products )),
function(i) {
callModule(ExistingProductUpdate,
id = i,
product = list_products[[i]] )
})
)
handlers
}) # end of server ----
# UI module ------------------------------------------------------
ExistingProductUI <- function(id, product){
ns <- NS(id)
box(title = as.character(product),
product,
footer = tagList(
actionBttn(
inputId = ns("change_selected"), label = "change"),
)
)
}
# server module ------------------------------------------------------
ExistingProductUpdate <- function(input, output, session, product){
ns <- session$ns
observeEvent(input$change_selected, {
# when box button is clicked for this product (id)
# FIRST: show a modal
showModal(
modalDialog(
title = "what do you want to change?",
tagList(
radioGroupButtons(inputId = ns("change_selected_choice"), label = "change x", choices = c(1,2,3,4)),
sliderInput(ns("change_selected_pct"), "change y:", min = -50, max = 100, value = 0, step = 5)
),
easyClose = TRUE,
footer = tagList(
actionButton(ns("change_selected_submit"), "submit!", icon = icon("check")),
modalButton("never mind")
)
)
)
})
# SECOND: when change_selected_submit is clicked,
observeEvent(input$change_selected_submit, {
# do some calculations with product using what I inputed in modal ---
# then, update a table ----
# functionToUploadThings(product, input$change_selected_choice)
# THIRD: Close with a confirmation
removeModal()
sendSweetAlert(
session,
title = "Success!",
type = "success",
btn_labels = "Ok",
closeOnClickOutside = TRUE,
width = NULL
)
})
}
shinyApp(ui, server)
Please note: I made some modifications to make your MWE work:
include library(shinydashboard)
p$title and product["title"] to product
change labels to label in radioGroupButtons
comment out functionToUploadThings(product, input$change_selected_choice)
Edit
I'm still not super sure what happens when nesting the observeEvents. I made a small toy example and played around with the reactlog. It seems that nesting the observers generates a new observer for button2 every time button1 is clicked. These observers are not removed and lead to unwanted behaviour. In contrast, when using separate observeEvents, the observer for button2 is only created once.
library(shiny)
library(reactlog)
ui <- fluidPage(
actionButton("button1", "click")
)
server <- function(input, output, session) {
observeEvent(input$button1, {
print("from first observer")
print(input$button2)
showModal(
modalDialog(
title = "what do you want to change?",
"some text",
easyClose = TRUE,
footer = tagList(
actionButton("button2", "submit!", icon = icon("check")),
modalButton("never mind")
)
)
)
# nested observer -> leads to remaining observers
observeEvent(input$button2, {
print("from second observer")
print(input$button2)
removeModal()
})
})
# independent observer -> generates only one observer
# observeEvent(input$button2, {
# print("from second observer")
# print(input$button2)
# removeModal()
# })
}
shinyApp(ui, server)
I am creating a shiny machine learning application. I am displaying data in datatables and want to pass the data to machine learning model by selecting the row and clicking the button to get result.
How can it be done in shiny ?
I think I understand what you are trying to do. Hope this minimal example I made will help you. Use DT for table rendering and row selection (here i suppressed the selection of more than one row because I deduced that is what you want). Use button and isolate to run model only if row is selected and button is pressed. I didn't fit a model here, instead I made a plot with highlited row data, but the principle is exactly the same.
library(shiny)
library(DT)
server <- function(input, output, session) {
output$x1 = DT::renderDataTable(mtcars, server = FALSE, selection = "single")
# client-side processing
output$x2 = renderPrint({
s = input$x1_rows_selected
if (length(s)) {
cat('These rows were selected:\n\n')
cat(s, sep = ', ')
}
})
# highlight selected rows in the scatterplot - here you add your model
output$x3 = renderPlot({
input$run_model # button input
s = isolate(input$x1_rows_selected) # use isolate to run model only on button press
par(mar = c(4, 4, 1, .1))
plot(mtcars[, 2:3])
if (length(s)) points(mtcars[s, 2:3, drop = FALSE], pch = 19, cex = 2)
})
}
ui <- fluidPage(
title = 'Select Table Rows',
h1('A Client-side Table'),
fluidRow(
column(9, DT::dataTableOutput('x1')),
column(3, verbatimTextOutput('x2'))
),
hr(),
h1('Model'),
fluidRow(
column(6, actionButton("run_model", "Go")),
column(9, plotOutput('x3', height = 500))
)
)
shinyApp(ui = ui, server = server)
I am working on an application in sinydashboard in which the user generates a random number on the click of a button. The random number corresponds to a row in a dataframe which I need to display on the dashboard using an infoBox. Each infoBox needs to persist on the screen until the user closes the application.
I tried generating a new output variable on each click in server.R, however I could not find a way of referencing it in ui.R. Minimal example below. I've not included generating a name for an output variable on each button click as that's not working at all.
library(shiny)
library(shinydashboard)
ui <- dashboardPage(dashboardHeader(title = ""),
dashboardSidebar(),
dashboardBody(fluidRow(
box(
width = 3,
actionButton(inputId = "generateButton",
label = "Generate")
),
box(infoBoxOutput("rnum1"))
)))
server <- function(input, output) {
randomData <- data.frame("RN" = runif(100, 1, 100))
observeEvent(input$generateButton, {
randomNumber <- floor(runif(1, 1, 100))
dataRow <- randomData[randomNumber,]
# Display dataRow in a persistent infoBox
# in a way that 5 clicks will produce 5 boxes
# Number of clicks is not known in advance
output$rnum1 <- renderInfoBox({
infoBox("Number", dataRow)
})
})
}
shinyApp(ui = ui, server = server)
Maybe this is what you want, at leat this a draft. You'll need a reactive variable to store the already generated numbers to be able to have something persistent.
library(shiny)
library(shinydashboard)
ui <- dashboardPage(dashboardHeader(title = ""),
dashboardSidebar(),
dashboardBody(actionButton(inputId = "generateButton",
label = "Generate")
,
uiOutput('infoBoxes'))
)
server <- function(input, output) {
randomData <- data.frame("RN" = runif(100, 1, 100))
rv <- reactiveValues()
observeEvent(input$generateButton, {
randomNumber <- floor(runif(1, 1, 100))
dataRow <- randomData[randomNumber,]
print(dataRow)
rv$persistent <- c(rv$persistent, dataRow)
# Display dataRow in a persistent infoBox
})
output$infoBoxes = renderUI({
if(length(rv$persistent) > 0 ) {
fluidRow(
Map(function(x) infoBox('title', rv$persistent[x]), 1:length(rv$persistent))
)
}
})
}
shinyApp(ui = ui, server = server)
I'm trying to add a "save inputs" feature to my Shiny app where the saved inputs would be saved in a DT data table. If a user clicks an Add button, the inputs would be appended to a data table. A user then can delete a row from this data table by selecting a row and clicking the Delete button. I also need to have this table's values be saved as a global variable so it stays persistent across all sessions.
The example code is shown below. When I close the session, the table (this_table) is correctly updated, however, those changes don't appear realtime during the app. I've tried putting both of these input buttons in an eventReactive function, but this did not work when one of the buttons was selected more than once.
Any ideas?
Global table:
this_table = data.frame(bins = c(30, 50), cb = c(T, F))
Shiny app code:
ui <- fluidPage(
sidebarLayout(
sidebarPanel(
sliderInput("bins",
"Number of bins:",
min = 1,
max = 50,
value = 30),
checkboxInput("cb", "T/F"),
actionButton("add_btn", "Add"),
actionButton("delete_btn", "Delete")
),
mainPanel(
DTOutput("shiny_table")
)
)
)
server <- function(input, output) {
observeEvent(input$add_btn, {
t = rbind(data.frame(bins = input$bins,
cb = input$cb), this_table)
this_table <<- t
})
observeEvent(input$delete_btn, {
t = this_table
print(nrow(t))
if (!is.null(input$shiny_table_rows_selected)) {
t <- t[-as.numeric(input$shiny_table_rows_selected),]
}
this_table <<- t
})
output$shiny_table <- renderDT({
datatable(this_table, selection = 'single', options = list(dom = 't'))
})
}
shinyApp(ui = ui, server = server)
You can use reactiveVal to add server side variables that are observable and mutable at the same time. The syntax for those variables is to initialize them as
rV <- reactiveValue("init_value")
and update them with
rV("new_value")
Those variables can be accessed inside reactive contexts (basically like inputs) with
rV()
The syntax is quite unusual for R and might take time to get used to, but it is definitely the recommended way to solve issues like these. You might also want to take a look at reactiveValues for a similar functionality but with a semantic closer to the R class list.
Here is how this technique can be applied to your question
library(shiny)
library(DT)
this_table = data.frame(bins = c(30, 50), cb = c(T, F))
ui <- fluidPage(
sidebarLayout(
sidebarPanel(
sliderInput("bins",
"Number of bins:",
min = 1,
max = 50,
value = 30),
checkboxInput("cb", "T/F"),
actionButton("add_btn", "Add"),
actionButton("delete_btn", "Delete")
),
mainPanel(
DTOutput("shiny_table")
)
)
)
server <- function(input, output) {
this_table <- reactiveVal(this_table)
observeEvent(input$add_btn, {
t = rbind(data.frame(bins = input$bins,
cb = input$cb), this_table())
this_table(t)
})
observeEvent(input$delete_btn, {
t = this_table()
print(nrow(t))
if (!is.null(input$shiny_table_rows_selected)) {
t <- t[-as.numeric(input$shiny_table_rows_selected),]
}
this_table(t)
})
output$shiny_table <- renderDT({
datatable(this_table(), selection = 'single', options = list(dom = 't'))
})
}
shinyApp(ui = ui, server = server)
Finally, I would like to add that # Vishesh Shrivastavs recommendation to use the rhandsontable package is also a viable approach, although you will definitely loose some flexibility in doing so.
I have made the following program:
ui.r
library(shiny)
shinyUI(fluidPage(
mainPanel(
textOutput("text1"),
checkboxGroupInput("checkGroup",
label = h3("Alternatives"),
choices = list("A" = 1,
"B" = 2,
"C" = 3,
"D" = 4),
selected = NULL),
actionButton("action", label = "Next")
)
))
server.r
library(shiny)
shinyServer(function(input, output) {
observe({
if(input$action>0 & input$action<=2){
valores<-renderText({
input$checkGroup
})
data<-unlist(strsplit(valores(), split=" "))
print(data)
}
})
})
I have managed to capture the values selected and put them into a vector, so I have solved an issue I got before.
The problem that I have now is that all the time it outputs which values I select or deselect from the checkbox groups, but I would like to only capture the last values selected after I press the Next button.
Any help? I have checked the documentation, but it is pretty scarce.
Here's one way to skin that cat.
We use isolate and reactive with the actionButton to ensure nothing is evaluated until the button is hit. By isolating the input itself from any further formatting we can call it any number of times for any purpose. Note that without the isolate it will evaluate as the inputs are changed.
server.R
library(shiny)
shinyServer(function(input, output) {
# store as a vector to be called wherever desired
# evaluated whenever inputs change
datasetInput <- reactive({
perm.vector <- as.vector(input$checkGroup)
perm.vector
})
# call as a text output
output$textOut <- renderText({
input$action # makes sure nothing moves till the button is hit
# isolate prevents datasetInput from reactively evaluating
isolate(datasetInput())
})
# call in a different place as a data table output
output$dataTableOut <- renderDataTable({
input$action # makes sure nothing moves till the button is hit
isolate(df <- data.frame(inputs = datasetInput()))
df
}, options = list(
lengthMenu = list(c(5, 15, -1), c('5', '15', 'All')),
pageLength = 15)
)
})
ui.R
library(shiny)
shinyUI(fluidPage(
sidebarLayout(
sidebarPanel(
checkboxGroupInput("checkGroup",
label = h3("Alternatives"),
choices = list("A" = 1,
"B" = 2,
"C" = 3,
"D" = 4),
selected = NULL),
actionButton("action", label = "Next")
),
mainPanel(
h4("Print as text"), textOutput("textOut"),
h4("Print as data table"), dataTableOutput("dataTableOut")
)
)
))
I found in: http://www.inside-r.org/packages/cran/shiny/docs/isolate
that it was possible to isolate a group of sentences, so the following works nicely:
library(shiny)
shinyServer(function(input, output) {
observe({
if(input$action>0 & input$action<=2){
isolate({
values<-renderText({
input$checkGroup
})
data<-unlist(strsplit(valores(), split=" "))
print(data)
})
}
})
})