shinyjs - setBookmarkExclude for delay IDs - shiny

I am attempting to exclude a ShinyJS delay from a reactive bookmarking context in Shiny. I see that the delay ID in the URL is autogenerated and always different: delay-ad190e10123bd97f960fed7a8a9e6fde=3000.
I attempted to exclude the delay via regular expression, however I don't believe the regex is being parsed:
setBookmarkExclude(
c("delay-[[:alnum:]]"))
I would like a way to either set the ID on the delay so it is the same every time or to regex the setBookmarkExclude to exclude the randomly generated delay ID

Please see the following example:
library(shiny)
library(shinyjs)
ui <- function(request) {
fluidPage(
useShinyjs(),
br(),
bookmarkButton(id="bookmarkBtn"),
hr(),
textOutput("ExcludedIDsOut"),
hr(),
sliderInput(inputId="slider", label="My value will be bookmarked", min=0, max=10, value=5),
textOutput("out_1"),
textOutput("out_2"),
textOutput("out_3")
)
}
server <- function(input, output, session) {
observeEvent(input$bookmarkBtn, {
session$doBookmark()
})
ExcludedIDs <- reactiveVal(value = NULL)
observe({
toExclude <- "bookmarkBtn"
delayExclude <- grep("delay", names(input), value = TRUE)
if(length(delayExclude) > 0){
toExclude <- c(toExclude, delayExclude)
}
setBookmarkExclude(toExclude)
ExcludedIDs(toExclude)
})
output$ExcludedIDsOut <- renderText({
paste("ExcludedIDs:", paste(ExcludedIDs(), collapse = ", "))
})
delay(1000, {
output$out_1 <- renderText({
"My"
})
})
delay(2000, {
output$out_2 <- renderText({
"delayed"
})
})
delay(3000, {
output$out_3 <- renderText({
"output"
})
})
}
enableBookmarking(store = "url") # store = "server"
shinyApp(ui, server)
Update: Whitelist approach
library(shiny)
library(shinyjs)
ui <- function(request) {
fluidPage(
useShinyjs(),
br(),
bookmarkButton(id="bookmarkBtn"),
hr(),
textOutput("ExcludedIDsOut"),
hr(),
sliderInput(inputId="slider", label="My value will be bookmarked", min=0, max=10, value=5),
textOutput("out_1"),
textOutput("out_2"),
textOutput("out_3")
)
}
server <- function(input, output, session) {
bookmarkingWhitelist <- c("slider")
observeEvent(input$bookmarkBtn, {
session$doBookmark()
})
ExcludedIDs <- reactive({
toExclude <- setdiff(names(input), bookmarkingWhitelist)
setBookmarkExclude(toExclude)
toExclude
})
output$ExcludedIDsOut <- renderText({
paste("ExcludedIDs:", paste(ExcludedIDs(), collapse = ", "))
})
delay(1000, {
output$out_1 <- renderText({
"My"
})
})
delay(2000, {
output$out_2 <- renderText({
"delayed"
})
})
delay(3000, {
output$out_3 <- renderText({
"output"
})
})
}
enableBookmarking(store = "url") # store = "server"
shinyApp(ui, server)
Here is a related GitHub issue, note session$getBookmarkExclude() as an alternative to keep track of the excluded inputs.

Related

Call for input inside moduleServer

I'm learning Shiny modules. And I'm stuck in a very silly thing: I don't know how to call an input inside moduleServer. In this reprex, the table does not show, I think its because the getInput argument is not properly used in the server. Here's a reprex:
library(shiny)
library(DT)
tablaResumen <- function(id, getInput, tabla1, tabla2) {
moduleServer(id, function(input, output, session) {
output$table <- renderDT({
if(getInput == FALSE){
tabla <- tabla1
}else{
tabla <- tabla2
}
DT::datatable(tabla, escape = FALSE, rownames = FALSE)
})
})
}
ui <- fluidPage(
checkboxInput("input1", label = "Change table"),
DTOutput("table1")
)
server <- function(input, output, session) {
tablaResumen("table1", input$input1, mtcars, iris)
}
shinyApp(ui, server)
library(shiny)
library(DT)
tablaResumen <- function(id, parent_in, get, tabla1, tabla2) {
moduleServer(id, function(input, output, session) {
output$mytable <- renderDT({
if(parent_in[[get]] == FALSE){
tabla <- tabla1
}else{
tabla <- tabla2
}
DT::datatable(tabla, escape = FALSE, rownames = FALSE)
})
})
}
tablaResumenUI <- function(id) {
ns <- NS(id)
DTOutput(ns("mytable"))
}
ui <- fluidPage(
checkboxInput("input1", label = "Change table"),
tablaResumenUI("table")
)
server <- function(input, output, session) {
tablaResumen("table", parent_in = input, "input1", mtcars, iris)
}
shinyApp(ui, server)
Things are a little tricky here.
To render the table, you must put the DTOutput under the same namespace as your mod server. The way we usually do it is by creating a mod UI function and use NS to wrap the id to create the namespace.
You module is depend on a reactive input value input$input1, but the server function itself is not reactive. This means if you provide it as an argument for the mod function, it will be run only one time, so getInput will never be changed after the app is initialized. It becomes a fixed value. To get the reactive value of input1, you need to provide the parent input as an argument as access from there.

rShiny Looping on ui filter conditions

I am trying to create a dashboard in rShiny which follow the following steps
Select a parameter
Filter data from a source table for this parameter
Create a list of this filtered data for one of the column
Iterate over this list to display graphs etc...
I have tried various options for making this work but the communication between ui and server is not happening as expected
I have created a setup as below fot testing
library(shiny)
df_mtcars <- mtcars
df_mtcars <- cbind(CarName = rownames(df_mtcars), df_mtcars)
df_mtcars$CarName <- sub(" ", "_", df_mtcars$CarName)
select the number of gears
Find the cars with that number of gears
Create a list of these cars
Display the data for each of the car by using loop. Loop is needed as other output types like graphs can be latter added
simpUI <- function(id) {
tagList(tableOutput(NS(id, "dat_output"))
numericInput(NS(id, "GearNumber"), "Gear Numbers", 3),
lapply(seq(1, length(v_lst_CarName), by = 1), function(i) {
v_CarName = v_lst_CarName[i]
v_obj_CarName = paste0('sp_cars_', v_CarName)
tableOutput(NS(id, v_obj_CarName))
}))
}
simpServer <- function(id) {
moduleServer(id, function(input, output, session) {
output$dat_output <- renderTable(df_mtcars)
v_lst_CarName <-
reactive(df_mtcars[GearNumber == input$GearNumber]$CarName)
for (v_CarName in v_lst_CarName)
v_obj_CarName = paste0('sp_cars_', v_CarName)
output$v_obj_CarName <- renderTable(v_obj_CarName)
})
}
ui <- fluidPage(fluidRow(simpUI("cars")))
server <- function(input, output, session) {
simpServer("cars")
}
shinyApp(ui = ui, server = server)
It is better to do server side processing. Try this
library(shiny)
library(ggplot2)
df_mtcars <- mtcars
df_mtcars <- cbind(CarName = rownames(df_mtcars), df_mtcars)
df_mtcars$CarName <- sub(" ", "_", df_mtcars$CarName)
simpUI <- function(id) {
ns <- NS(id)
tagList(tableOutput(ns("dat_output")),
numericInput(ns("GearNumber"), "Gear Numbers", 3),
uiOutput(ns("plotxy")),
tableOutput(ns("v_obj_CarName")),
verbatimTextOutput(ns("mylist")),
plotOutput(ns("myplot"))
)
}
simpServer <- function(id) {
moduleServer(id, function(input, output, session) {
ns <- session$ns
output$dat_output <- renderTable(head(df_mtcars))
mydf <- reactive(df_mtcars[df_mtcars$gear == input$GearNumber,])
v_lst_CarName <- eventReactive(mydf(), {paste0("sp_cars_",mydf()$CarName)})
output$plotxy <- renderUI({
req(mydf())
tagList(
selectInput(ns("xvar"), label = "X-axis variable", choices = names(mydf()), selected=names(mydf())[2] ),
selectInput(ns("yvar"), label = "Y-axis variable", choices = names(mydf()), selected=names(mydf())[5] )
)
})
output$v_obj_CarName <- renderTable({mydf()})
output$mylist <- renderPrint(list(v_lst_CarName() ))
output$myplot <- renderPlot({
req(input$xvar,input$yvar)
ggplot(mydf(),aes(x=.data[[input$xvar]], y=.data[[input$yvar]])) + geom_point()
})
})
}
ui <- fluidPage(fluidRow(simpUI("cars")))
server <- function(input, output, session) {
simpServer("cars")
}
shinyApp(ui = ui, server = server)

Modify a Shiny reactive expression with two forms of user input

I want to use a reactive expression that can be updated in either of two ways. Below is a very simple example with either numeric input or a reset button to set the expression back to its original state (in practice the expression is more complex, so can't use reactive values). It seems that only the second definition of num is recognised, so in the example the numeric input is ignored).
What am I missing?
Many thanks!
ui <- fluidPage(
numericInput("number", "Input", 1),
actionButton("button", "Reset"),
textOutput("check")
)
server <- function(input, output){
num <- reactive({
input$number
})
num <- eventReactive(input$button, {
1
})
output$check <- renderText({
num()
})
}
shinyApp(ui, server)
Edit:
We can use observeEvent() with each input to update num().
library(shiny)
ui <- fluidPage(
numericInput("number", "Input", 1),
actionButton("button", "Reset"),
textOutput("check")
)
server <- function(input, output) {
num <- reactiveVal()
observeEvent(input$number, {
num(input$number)
})
observeEvent(input$button, {
num(1)
})
observeEvent(c(input$button, input$number), {
output$check <- renderText({
num()
})
})
}
shinyApp(ui, server)

How to reuse a dataset in different objects when renderUI is used to create tabs in ShinyR

I developed a Shiny application to include couple of plots and data under different tabs.Tabs are created dynamically using another parameter.But each time i have to subset the data to prepare the plots. Say using 'mpg' subsetdata i plotted 2 different types of graphs in 'mpg' tab and i don't want to subset data every time(currently i sub set every time) when i draw the plot.For all calculations in one tab, i would like to subset the data only once.Appreciate some help
write.csv(mtcars,'mtcars.csv')
write.csv(mtcars,'mtcars.csv')
library(shiny)
library(plyr)
library(dplyr)
library(DT)
library(data.table)
ui <- pageWithSidebar(
headerPanel = headerPanel('data'),
sidebarPanel = sidebarPanel(fileInput(
'mtcars', h4('Uplaodmtcardata in csv format')
),
uiOutput('tabnamesui')),
mainPanel(uiOutput("tabsets"))
)
server <- function(input, output, session) {
mtcarsFile <- reactive({
input$mtcars
})
xxmtcars <-
reactive({
read.table(
file = mtcarsFile()$datapath,
sep = ',',
header = T,
stringsAsFactors = T
)
})
tabsnames <- reactive({
names(xxmtcars())
})
output$tabnamesui <- renderUI({
req(mtcarsFile())
selectInput(
'tabnamesui',
h5('Tab names'),
choices = as.list(tabsnames()),
multiple = T
# selected = SalesGlobalDataFilter1Val()
)
})
tabnamesinput <- reactive({
input$tabnamesui
})
output$tabsets <- renderUI({
req(mtcarsFile())
tabs <-
reactive({
lapply(tabnamesinput(), function(x)
tabPanel(title = basename(x)
,fluidRow(splitLayout(cellWidths = c("50%", "50%"),
plotOutput(paste0('plot1',x)),
plotOutput(paste0('plot2',x)
))),fluidRow(splitLayout(cellWidths =
c("50%", "50%"),
plotOutput(paste0('plot3',x)),
plotOutput(paste0('plot4',x)
))),
dataTableOutput(paste0('table',x))))
})
do.call(tabsetPanel, c(tabs()))
})
observe(
lapply(tabnamesinput(), function(x) {
output[[paste0('table',x)]] <-
renderDataTable({as.data.table((select(xxmtcars(),x)))#CODE REPEATED
})}))
observe(
lapply(tabnamesinput(), function(x) {
output[[paste0('plot1',x)]] <-
renderPlot({as.data.table((select(xxmtcars(),x)))%>%plot()#CODE REPEATED
})
})
)
observe(
lapply(tabnamesinput(), function(x) {
output[[paste0('plot2',x)]] <-
renderPlot({as.data.table((select(xxmtcars(),x)))%>%plot()#CODE #REPEATED
})
})
)
observe(
lapply(tabnamesinput(), function(x) {
output[[paste0('plot3',x)]] <-
renderPlot({as.data.table((select(xxmtcars(),x)))%>%plot()#CODE REPEATED
})
})
)
observe(
lapply(tabnamesinput(), function(x) {
output[[paste0('plot4',x)]] <-
renderPlot({as.data.table((select(xxmtcars(),x)))%>%plot()#CODE REPEATED
})
})
)
}
runApp(list(ui = ui, server = server))
You can save your sub data into a reactive object and call it when you need.
library(shiny)
library(plyr)
library(dplyr)
library(DT)
library(data.table)
ui <- pageWithSidebar(
headerPanel = headerPanel('data'),
sidebarPanel = sidebarPanel(fileInput(
'mtcars', h4('Uplaodmtcardata in csv format')
),
uiOutput('tabnamesui')),
mainPanel(uiOutput("tabsets"))
)
server <- function(input, output, session) {
mtcarsFile <- reactive({
input$mtcars
})
xxmtcars <-
reactive({
read.table(
file = mtcarsFile()$datapath,
sep = ',',
header = T,
stringsAsFactors = T
)
})
tabsnames <- reactive({
names(xxmtcars())
})
output$tabnamesui <- renderUI({
req(mtcarsFile())
selectInput(
'tabnamesui',
h5('Tab names'),
choices = as.list(tabsnames()),
multiple = T
# selected = SalesGlobalDataFilter1Val()
)
})
tabnamesinput <- reactive({
input$tabnamesui
})
output$tabsets <- renderUI({
req(mtcarsFile())
tabs <-
reactive({
lapply(tabnamesinput(), function(x)
tabPanel(title = basename(x)
,fluidRow(splitLayout(cellWidths = c("50%", "50%"),
plotOutput(paste0('plot1',x)),
plotOutput(paste0('plot2',x)
))),fluidRow(splitLayout(cellWidths =
c("50%", "50%"),
plotOutput(paste0('plot3',x)),
plotOutput(paste0('plot4',x)
))),
dataTableOutput(paste0('table',x))))
})
do.call(tabsetPanel, c(tabs()))
})
# Save your sub data here
subsetdata<-reactive({
list_of_subdata<-lapply(tabnamesinput(), function(x) {
as.data.table((select(xxmtcars(),x)))
})
names(list_of_subdata)<-tabnamesinput()
return(list_of_subdata)
})
observe(
lapply(tabnamesinput(), function(x) {
output[[paste0('table',x)]] <-
renderDataTable({
subsetdata()[[x]]
})}))
observe(
lapply(tabnamesinput(), function(x) {
for(i in paste0("plot",1:4)){
output[[paste0(i,x)]] <-
renderPlot({subsetdata()[[x]]%>%plot()#CODE REPEATED
})
}
})
)
}
runApp(list(ui = ui, server = server))

Shiny failed to connect to ODBC

I am trying to have Shiny connects to Teradata.
Below is the code I have but I always get "ERROR: [on_request_read] connection reset by peer" after I choose the indicator and click the action button. Appreciated any input for this. Thanks.
ui <- shinyUI(fluidPage(
titlePanel("Generic grapher"),
sidebarLayout(
sidebarPanel(
numericInput("wafer", label = h3("Select Indicator:"),
value = NULL),
actionButton("do", "An action button")
),
mainPanel(
verbatimTextOutput("value"),
verbatimTextOutput("que"),
verbatimTextOutput("wq_print"),
dataTableOutput(outputId="pos")
)
)
)
)
library(markdown)
library(RODBC)
library(DBI)
library(sqldf)
ch<-odbcConnect("xxx", uid=" ",pwd=" ")
wq = data.frame()
server <- shinyServer(function(input, output){
values <- reactiveValues()
values$df <- data.frame()
d <- eventReactive(input$do, { input$wafer })
output$value <- renderPrint({ d() })
a <- reactive({ paste("SELECT * FROM dwname.tablename WHERE indicator_x = ", d(), sep="") })
output$que <- renderPrint({ a() })
observe({
if (!is.null(d())) {
wq <- reactive({ sqlQuery( a() ) })
output$wq_print <- renderPrint({ print(str(wq())) })
values$df <- rbind(isolate(values$df), wq())
}
})
output$pos <- renderDataTable({ values$df })
})
shinyApp(ui, server)