Shinyjs hide and show not properly working - shiny

I have a problem with shinyjs hide() and show(). I use this to hide and show different data anyalysis that can be choosen from a side bar.
If I do one part of my code it works fine but when I hide() and then do a different calculation it shows me the text part of the firt one again.
Does anyone has any idea oder experienced similar things?
I expect my code to hide/delete the part I did not want to see anymore and just showing me the new analysis I choosed.
Thanks and best,
Marina
Here´s my code from UI:
tabPanel(title="Datenanalyse",value="analysis",
includeMarkdown("../Texte/Mietpreise/Datenanalyse.md"),
fluidPage(
sidebarLayout(
sidebarPanel(
uiOutput("variables"),
selectInput("methods","Analysemethode",choices= c("Boxplot"="box","Balkendiagramm"="balken",
"Histogramm"="hist","Streudiagramm"="streu",
"Kreisdiagramm"="kreis",
"arithm. Mittel"="mw","N(%)"="anz","Regression"="reg"),
selected="box"),
actionButton("vorschau","Vorschau"),
actionButton("clear","Löschen"),
actionButton("fest","Festsetzen"),
hr(),
br(),
br(),
br(),
br(),
actionButton("zurueck3","Zurück"),
actionButton("hilfe3", "Hilfe"),
actionButton("weiter4","Weiter")
),
mainPanel(
textOutput("txt"),
textOutput("txt3"),
uiOutput("createvars"),
tableOutput("txt2"),
plotOutput("plot")
)
)
)
)
And here´s the part from server:
observeEvent(input$clear,{
shinyjs::hide("plot")
shinyjs::hide("txt")
shinyjs::hide("txt2")
shinyjs::hide("txt3")
shinyjs::hide("createvars")
})
observeEvent(input$vorschau,{
shinyjs::show("plot")
shinyjs::show("txt")
shinyjs::show("txt2")
shinyjs::show("createvars")
shinyjs::show("txt3")
})
observeEvent(input$vorschau,{
output$plot <- renderPlot({
if(input$methods =="box"){
if(length(input$variables==1)){
p <- boxplot(x = d()[input$variables],xlab=input$variables)
}
if(length(input$variables)>1){
p <- boxplot(x = d()[input$variables])
}
}
if(input$methods =="balken"){
p <- barplot(table(d()[input$variables]),xlab=input$variables)
}
if(input$methods =="hist"){
p <- hist(as.numeric(unlist(d()[input$variables])),xlab=input$variables, ylab="Anzahl", main="")
}
if(input$methods =="streu"){
p <- plot(d()[input$variables])
}
if(input$methods =="kreis"){
p <- pie(table(d()[input$variables]),main = input$variables)
}
})
output$txt <- renderText({
if(input$methods =="mw"){
paste0("Das arithmetische Mittel von ",input$variables," beträgt: ", round(mean(as.numeric(unlist(d()[input$variables]))),2))
}
})
output$txt2 <- renderTable({
if(input$methods =="anz"){
t<-data.frame(table(d()[input$variables]))
col_headings <- c(paste0(input$variables),"Freq")
colnames(t)<-col_headings
t
}
})
if(input$methods =="reg"){
output$txt3 <- renderText({
paste0("Geben Sie zuerst die Einflussgröße und dann die Zielgröße im Feld Variablenauswahl an.")
})
output$plot<-renderPlot({
lmodel <- lm(as.numeric(unlist(d()[input$variables][2]))~as.numeric(unlist(d()[input$variables][1])))
plot(d()[input$variables],xlab = names(d()[input$variables][1]),
ylab=names(d()[input$variables][2]), main= paste(names(d()[input$variables][2]),' =', round(coef(lmodel)[[2]],2), ' * ', names(d()[input$variables][1]), '+', round(coef(lmodel)[[1]],2)))
abline(lmodel)
})
}
})

Related

User defined function output in Shiny not in scope

I would like to use a user defined function in Shiny to perform a simple calculation with output two variables. The function I wrote works when it is not part of a shiny app. However when part of a Shiny, the returned object (dfr) is ‘not in scope’. What am I missing?
library(shiny)
# Function ----------------------------------------------------------------
convert <- function(coef_1, coef_2, vec) {
part_1 <- coef_1/(2*sin((vec/2)*pi/180))
part_2 <- 2*(180/pi)*(asin(coef_2/(2*part_1)))
dfr <- data.frame(part_1, part_2)
return(dfr)
}
# End Function ------------------------------------------------------------
ui <- fluidPage(
sidebarLayout(
sidebarPanel(
textInput("num", h3("Enter number to convert:"), value = NULL)
),
mainPanel(
verbatimTextOutput("text1", placeholder = TRUE),
verbatimTextOutput("text2", placeholder = TRUE)
)
)
)
server <- function(input, output) {
nums_str <- as.character(input$num)
nums_vector <- as.numeric(unlist(strsplit(nums_str, split = ",")))
convert(1.5, 1.1, nums_vector)
output$text1 <- renderText({
req(input$num)
dfr$part_1
})
output$text2 <- renderText({
req(input$num)
dfr$part_2
})
}
shinyApp(ui = ui, server = server)
When you use inputs, you need to do it in reactive environment, such as reactive(), renderDataTable(), etc.
Here, you need to run your function in a reactive() and then call it with dfr() in the outputs.
server <- function(input, output) {
dfr <- reactive({
convert(1.5, 1.1, as.numeric(input$num))
})
output$text1 <- renderText({
req(input$num)
dfr()$part_1
})
output$text2 <- renderText({
req(input$num)
dfr()$part_2
})
}
Since this is quite basic stuff with R Shiny, checking some tutorials might be very useful.

Shiny App not reacting when clicking points in R

I am trying now since days to get my Shiny App working so that when I move my mouse to certain points in the plot they are displayed in a table but unfortunately it is not working.
I am not sure what I am doing wrong, can you help me?
border <- table$A < 0.03
ui <- fluidPage(
mainPanel(
plotOutput("Plot",click="plot_click"),
tableOutput("HitSpots")
)
)
server <- function(input, output){
output$Plot <- renderPlot({
ggplot(table,aes(x=table$A, y=table$B), colour=border)) +
geom_point()
})
hit <- reactive({
nearPoints(table, input$plot_click)
})
output$HitSpots <- renderTable({
hit()
}
}
shinyApp(ui = ui, server = server)
There are some problems with your parentheses. But the main problem is that you do ggplot(table, aes(x=table$A, y=table$B)), and then nearpoints is looking for columns named table$A and table$B. Do ggplot(table, aes(x=A, y=B)) instead.
library(shiny)
library(ggplot2)
table <- data.frame(
A = c(1,2,3),
B = c(3,2,1)
)
ui <- fluidPage(
mainPanel(
plotOutput("Plot", click="plot_click"),
tableOutput("HitSpots")
)
)
server <- function(input, output){
output$Plot <- renderPlot({
ggplot(table, aes(x=A, y=B)) + geom_point()
})
hit <- reactive({ nearPoints(table, input$plot_click) })
output$HitSpots <- renderTable({
hit()
})
}
shinyApp(ui = ui, server = server)

shinyjs - setBookmarkExclude for delay IDs

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.

shiny: add/remove time-series to dygraphs upon input values

I'm building a shiny app that would display in dygraphs a basic dataset and then offer an option to add new time series upon selecting the checkbox input. However, as I coded it now, I'm 'stuck' at the original dataset and unable to add/remove new content. Any hints how to solve this are very welcome, thanks.
library(shinydashboard)
library(dygraphs)
library(dplyr)
ui <-dashboardPage(
dashboardHeader(),
dashboardSidebar(),
dashboardBody(
useShinyjs(),
checkboxGroupInput(inputId = 'options',
label = 'Choose your plot(s)',
choices = list("mdeaths" = 1,
"ldeaths" = 2)
),
uiOutput("Ui1")
)
)
server <- function(input, output, session) {
output$Ui1 <- renderUI({
output$plot1 <- renderDygraph({
final_ts <- ldeaths
p <- dygraph(final_ts, main = 'Main plot') %>%
dygraphs::dyRangeSelector()
if(1 %in% input$options) {
final_ts <- cbind(final_ts, mdeaths)
p <- p %>%
dySeries('mdeaths', 'Male Deaths')
} else if(2 %in% input$options) {
final_ts <- cbind(final_ts, fdeaths)
p <- p %>%
dySeries('fdeaths', 'Female Deaths')
}
p
})
dygraphOutput('plot1')
})
}
shinyApp(ui, server)
I'd suggest to dynamically filter the data based on the user selection instead of dynamically adding/removing traces from the plot:
library(shinydashboard)
library(shinyjs)
library(dygraphs)
library(dplyr)
lungDeaths <- cbind(ldeaths, mdeaths, fdeaths)
ui <- dashboardPage(
dashboardHeader(),
dashboardSidebar(),
dashboardBody(
useShinyjs(),
selectizeInput(
inputId = "options",
label = "Choose your trace(s)",
choices = colnames(lungDeaths),
selected = colnames(lungDeaths)[1],
multiple = TRUE,
options = list('plugins' = list('remove_button'))
),
uiOutput("Ui1")
)
)
server <- function(input, output, session) {
output$Ui1 <- renderUI({
filteredLungDeaths <- reactive({
lungDeaths[, input$options]
})
output$plot1 <- renderDygraph({
p <- dygraph(filteredLungDeaths(), main = 'Main plot') %>%
dygraphs::dyRangeSelector()
if('mdeaths' %in% colnames(filteredLungDeaths())){
p <- dySeries(p, 'mdeaths', 'Male Deaths')
}
if('fdeaths' %in% colnames(filteredLungDeaths())){
p <- dySeries(p, 'fdeaths', 'Female Deaths')
}
p
})
dygraphOutput('plot1')
})
}
shinyApp(ui, 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)