Error: Cannot open the connection - r

I am new to Shiny R and was successful in creating my first app (YAY!)! I then tried to deploy it (or publish it) and got the following error message on the web page it opened (it was working correctly within R studio and seemed to deploy ok). I checked only the app.R box when I went to publish it.
Error: Cannot open the connection.
I have had a look at other answers on here and elsewhere but I either have used the solutions and they haven't worked or haven't understood the answers (I am pretty new to R and Shiny R). I am at my wits end and really want to get this up and running as I love what Shiny is capable of.
Can anyone help??
The code I used is;
require(shiny)
meanweights <- read.csv("meanweights.csv")
ui <- fluidPage(
selectInput(inputId = "statesel",
label="Choose a state",
choices = sort(unique(meanweights$state)),
selected = "VIC",
multiple = FALSE),
plotOutput("lineplot")
)
server <- function(input, output) {
output$lineplot <- renderPlot({
read.csv("meanweights.csv") %>%
filter(state == input$statesel) %>%
ggplot(aes(day, mean_weight, color=property_type))+
geom_line()+theme_bw(base_size = 14)
})
}
shinyApp(ui = ui, server = server)
Thanks for you time.

Related

Rstudio Connect Shiny dashboard only shows plot if table is visible

I want to have a Shiny dashboard on Rstudio Connect where data is read from my companies data store via JDBC, and then plotted. Ultimately the user would be able to give some parameters and the appropriate output would be displayed.
What I've discovered is that if I show a table of the data and the plot, everything works out fine. However, if I do not display the table I get an error:
Error: An error has occurred. Check your logs or contact the app author for clarification.
The line in the log files related to the error is not meaningful to me, but appears to be java related (and so maybe related to the JDBC connection):
Warning: Error in .jcheck: Java Exception <no description because toString() failed>
.jcall(conn#jc, "Ljava/sql/Statement;", "createStatement")
new("jobjRef", jobj = <pointer: 0x55cbc9a35608>, jclass = "java/lang/Throwable")
What works?
Here's as minimum a reproducible example as I could get. I appreciate that the architecture is internal to my company, so it won't run for others, but I think it can be helpful. The below code works:
# app.R
library(RJDBC)
library(shiny)
getconnection <- function(){
ORACLE_JAR <- '/usr/lib/oracle/21/client64/lib/ojdbc8.jar'
db_host = "db_host.company.information:1521"
drv <- RJDBC::JDBC("oracle.jdbc.OracleDriver",
ORACLE_JAR,
identifier.quote="`")
sid <- "sid.prd.tns"
url <- paste("jdbc:oracle:thin:#/",
db_host,
sid, sep = '/')
connection<-dbConnect(drv,
url,
user='****', # anonymised for stack overflow
password='****',
believeNRows=FALSE )
return(connection)
}
ui <- fluidPage(
titlePanel("MinRepEx"),
tableOutput('result'),
plotOutput('plot')
)
server <- function(input, output) {
conn <- getconnection()
mydata <- reactive({query_result(conn)})
output$result <- renderTable(head(mydata()))
output$result <- NULL
myplot <- reactive({plot(OBS_VALUE ~ OBS_DATE, data = mydata())})
output$plot <-renderPlot({myplot()})
}
shinyApp(ui = ui, server = server)
When I deploy this, as I say it works:
What doesn't work?
If I remove the lines related to result, i.e. the table output things stop working:
## Everyhing above this line is kept unchanged
ui <- fluidPage(
titlePanel("MinRepEx"),
# tableOutput('result'),
plotOutput('plot')
)
server <- function(input, output) {
conn <- getconnection()
mydata <- reactive({query_result(conn)})
# output$result <- renderTable(head(mydata()))
myplot <- reactive({plot(OBS_VALUE ~ OBS_DATE, data = mydata())})
output$plot <-renderPlot({myplot()})
}
shinyApp(ui = ui, server = server)
which leads to:
Possible solutions that need tweeking:
The code works as intended on my machine it does not work when I ship it to RStudio Connect.
The code is a minimised version of the code where there is a need for query_result to be a reactive function, so I can't take it out of the reactive world. However, if I do, I can display the chart on its own. `
Likewise, if I open the connection conn inside mydata it will generate the image. However opening the connection each time is very slow. If there was someway to check if a connection was open and if not open one, or to make the connection visible inside mydata?
What else have I tried?
I've tried a few other things that might help inform about the solution:
If I just do renderTable, there are no problems (except that I do't have the chart I want).
If I change the order of plotOutput and tableOutput in the UI, the table and plot appear
If I change the order of renderTable and renderPlot in the server, neither table nor plot are produced and I have the same error message in the logs twice.
If I introduce a Sys.sleep(60) command to myplot, it doesn't fix the issue
I have put a the line data <- mydata() inside the renderPlot({...}) before myplot()
The above 'possible solutions' might yield something, but rather frustratingly, I would like to know why the connection remains visible if I show the table or the table and plot, but not the plot on its own. Likewise, the code works without this issue locally, but not remotely. It would be interesting to understand why.

Deploy shiny app that can call runApp() inside application itself (specifically for tabulizer package)

I'm trying to deploy a Shiny app that allows the user to upload a pdf document and extract a table from a selected page. For this I'm using the package tabulizer. A basic reproducible example:
library(shiny)
library(tabulizer)
ui <- fluidPage(
fileInput("report", NULL,buttonLabel = "Upload report"),
numericInput("page","Specify page number",value = 1),
actionButton("extract","Extract"),
verbatimTextOutput("data")
)
server <- function(input, output, session) {
generate_data <- reactive({
req(input$report)
# This locate_area function calls runApp() from the tabulizer package
area <- locate_areas(file = input$report$datapath,
pages = input$page,
widget = "reduced")
table <- extract_tables(file = input$report$datapath,
pages = input$page,
area = area)
return(table)
})%>% bindCache(input$page) %>% bindEvent(input$extract)
output$data <- renderPrint({
# Just for the sake of this example to show it works
generate_data()
})
}
shinyApp(ui = ui, server = server)
If I run this locally, the locate_area() will make the pdf page pop-up on my viewer in RStudio and all is well. However, if I publish the app it doesn't run after clicking the action button. I know the problem comes from the locate_area() as it essentially calls another runApp within the shiny app. I have tried using different widgets for locate_area() to no avail. Does anybody know a way to circumvent this issue?
Judging by the relevant issues - issue 15 and issue 53 - it appears that your best way to go is really to copy the functionality from the original tabulizer function into your own app, as currently the package does not provide an easy integration with other Shiny apps.

Run App gives no result R shiny app and crashes RStudio

I'm having an issue with the running of a R shiny app. Here's what I do:
open RStudio
load the shiny code (e.g. app.R)
set the wd
library(shiny)
press on "Run App"
Then nothing happens.
And if I try to terminate the execution, R does not answer anymore and says to force the closing of RStudio.
Here's one of my codes (I tried some, so I don't think this is the issue, but I report one anyway):
library(shiny)
# Define UI for application that draws a histogram
ui <- fluidPage(
titlePanel("Un'applicazione con uno slider"),
sidebarLayout(
h1("Sposta lo Slider!"),
sliderInput("slider1", "Spostami!", 0, 100, 0)
),
mainPanel(
h3("Valore dello slider:"),
textOutput("text")
)
)
# Define server logic required to draw a histogram
server <- function(input, output) {
output$text <- renderText(input$slider1)
}
# Run the application
shinyApp(ui = ui, server = server)
Do you have any advice to give me in order to make anything happen? I have no errors shown, so I don't know what to do...
I just see "runApp(...mypath.../app)" and blank space after it.
Thank you in advance.
Edit 1:
I also tried this, but nothing happened (as before):
library(shiny)
runExample("01_hello")
Edit 2: Copy-pasting the code directly in the console doen not work either
I was experiencing the same issue with R 4.1 on Windows 10. Updating all packages seems to have solved it:
update.packages(ask = FALSE, checkBuilt = TRUE)

R Shiny not showing plot until after several page refreshes

I'm new to Shiny and have been developing a web app that displays a plotly chart; I'm still developing the app on my local machine. When I run the app for the first time after opening RGui, the web app runs but does not render the chart, even after I have clicked the "Draw" button. I have to refresh the webpage once or twice and then the chart will render. Once the chart has rendered, the problem is gone for the duration of that R session. Refreshing the page or restarting the shiny program will continue to render the chart, until RGui is closed. The problem reliably recurs the next time I open RGui and run the app.
All the existing questions and answers I have searched on shiny and failed rendering have not answered my question.
After several frustrated attempts at trying to find what was wrong in my program, I boiled it down to this code that looks (to me) like it should be functional, but still presents the issue:
library(shiny)
library(plotly)
ui = fluidPage(
plotlyOutput("Plot"),
actionButton("drawPlotButton", "Draw")
)
server = function(input, output)
{
output$Plot = renderPlotly({
input$drawPlotButton
return(plot_ly(mtcars, x = ~hp, y = ~mpg, type = "scatter", mode = "markers"))
})
}
shinyApp(ui = ui, server = server)
I can't tell if I am missing something simple or what. All help is appreciated.
Generally runs fine for me as in the plot renders at initialization.
However, if your objective is to plot the graph only when the Draw button is clicked then:
You need to add a eventReactive method
See r Shiny action button and data table output
library(shiny)
library(plotly)
ui = fluidPage(
plotlyOutput("Plot"),
actionButton("drawPlotButton", "Draw")
)
server = function(input, output)
{
plot_d <- eventReactive(input$drawPlotButton, {
plot_ly(mtcars, x = ~hp, y = ~mpg, type = "scatter", mode = "markers")
})
output$Plot = renderPlotly({
plot_d()
})
}
shinyApp(ui = ui, server = server)

R Shiny run task/script in different process

In my Shiny app users can generate heavy powerpoint report. When it contains a lot of slides it could take > 30 minutes to be done. And therefore I'd like to process those tasks in independent processes/tasks which could work even when app is closed - e.g. user clicks button to generate report, closes app and when report is ready app informs user by email.
Are there any good practices or proven solutions to do this?
My first thought was using future package with plan(multisession) set - but I'm not sure what happens when user closes the app - future session closes too or not?
I was lucky enough to be at London EARL this week and I think one of the best presentations I saw there was about exactly this (by Joe Cheng). You would need the promises package for this to work and as it says on the documentation a special version of shiny devtools::install_github("rstudio/shiny#async") that supports asynchronous programming.
You can find a first documentation here on how this works by using dplyr and promises (future is also compatible).
As a small example (taken from the documentation), running an intensive calculation using the following:
read.csv.async("data.csv") %...>%
filter(state == "NY") %...>%
arrange(median_income) %...>%
head(10) %...>%
View()
would essentially return the console cursor back, allowing you to run any other command you want and would automatically open the View tab once this was finished. I might be able to dig out a shiny example in a bit, but keep in mind this is still under development and will be released before the end of the year (with a more comprehensive documentation I would imagine).
So I made some example workaround using future package. Code executes in separate session (cluster) even when app is closed. I think the next step is just to figure out how app should check if process is still running or is finished. Any ideas?
library(future)
cl <- parallel::makeCluster(2L)
plan(cluster, workers = cl)
server <- function(input, output) {
observeEvent(input$run, {
iteration <- as.numeric(input$iteration)
path <- input$path
future::future({
writeLog <- function(n, path) {
file.remove(path)
for (i in 1:n) {
cat("#", i, "-", as.character(Sys.time()), "\n", file = path, append = TRUE)
Sys.sleep(1)
}
}
writeLog(iteration, path)
}, globals = c("iteration", "path"))
})
}
ui <- fluidPage(
sidebarLayout(
sidebarPanel(
tags$div("This app writes to file in cluster which means it is computed in parallel to this session.
It will execute even when app is closed.")
, br()
, shiny::textInput("path", "Path to log file", value = "/src/dev/export_performance/future.log")
, shiny::textInput("iteration", "Iteration number", value = 60)
),
mainPanel(
br()
, actionButton("run", "Run future")
)
)
)
shinyApp(ui = ui, server = server)

Resources