I am quite a newbie to Shiny
apps but I managed to build an interface that allows me to choose from a list of image urls based on the images that can be found at the url. The app works fine when I do Run App
on RStudio
but as soon as I try to call it from an external function, the images are no longer shown (only thumbnails). Since the script is quite long, I managed after a bit of debbugging to recreate the effect on a MRE that is based on the shiny project example.
library(shiny)
app_ui <- fluidPage(
# Application title
titlePanel("Old Faithful Geyser Data"),
# Sidebar with a slider input for number of bins and an image
sidebarLayout(
sidebarPanel(
sliderInput("bins", "Number of bins:", min = 1, max = 50, value = 30),
# Inserting the image
img(src = "/prova/1.jpg", height = "300px", width = "100%")
),
# Show a plot of the generated distribution
mainPanel(
plotOutput("distPlot")
)
)
)
# Define server logic required to draw a histogram
app_server <- function(input, output) {
output$distPlot <- renderPlot({
# generate bins based on input$bins from ui.R
x <- faithful[, 2]
bins <- seq(min(x), max(x), length.out = input$bins + 1)
# draw the histogram with the specified number of bins
hist(x, breaks = bins, col = 'darkgray', border = 'white',
xlab = 'Waiting time to next eruption (in mins)',
main = 'Histogram of waiting times')
})
}
# Run the application
app <- shinyApp(ui = app_ui, server = app_server)
If I then have a different R script (external.R
) where I call the app contained in file MainApp.R
like so, the image breaks down.
source("path_to_app/MainApp.R")
app
In fact I noticed an even stranger behaviour. If I first Run App
the app, the images are displayed correctly also when sourcing from an external file. If I clean the environment and try to source directly, the images are not shown. It seems almost like the images are cached somewhere.
My folder structure is
Shinyapp
|- MainApp.R
|- external.R
|- www
| |- prova
| |- 1.jpg
Your folder structure and request path is correct. As the shiny
docs note:
Static files under the
www/
directory are automatically made available under a request path that begins with/
The odd thing is that the image is displayed at all when you source external.R
. I suspect it might be some RStudio magic, and if you open the URL in a browser you will not see the image.
In any case, the issue is that you're using shiny::shinyApp()
, which creates an app from a server
and ui
R object.
However, you need the context of the directory and subdirectory, so you want to use shiny::runApp()
, to pass the current folder.
shiny::runApp()
expects either a ui.R
and server.R
, or an app.R
. So in your case, rename mainApp.R
to app.R
, and then the contents of external.R
can simply be:
shiny::runApp()