Example data
Of course, all guidelines regarding sample data mentioned in the answer on the question “how to make a great R reproducible example” also hold when creating questions related to Shiny
. To summarize: Make sure no additional files are needed to run your code. Use sample datasets like mtcars
, or create some sample data with data.frame()
. If your data is very complex and that complexity is really required to illustrate the issue, you could also use dput()
. Avoid using functions like read.csv()
, unless of course you have questions related to functions like fileInput
.
Example code
Always reduce your code to the bare minimum to reproduce your error or unexpected behavior. This includes removing calls to additional .CSS
files and .js
files and removing unnecessary functions in the ui
and the server
.
Shiny apps often consist of two or three files (ui.R
, server.R
and possibly global.R
), for example this demo application. However, it is preferable to post your code as a single script, so it can easily be run by others without having to manually create those files. This can easily be done by:
- wrapping your ui with
ui <- fluidPage(…)
,
- the server with
server <- function(input,output, session) {…}
,
- and subsequently calling
shinyApp(ui, server)
.
So a simple skeleton to start with could look as follows:
library(shiny)
ui <- fluidPage(
)
server <- function(input,output,session) {
}
shinyApp(ui, server)
Working Example
So, taking all the above into account, a good Minimal, Complete, and Verifiable example for a Shiny application could look as follows:
library(shiny)
df <- data.frame(id = letters[1:10], value = seq(1,10))
ui <- fluidPage(
sliderInput('nrow', 'Number of rows', min = 1, max = 10, value = 5),
dataTableOutput('my_table')
)
server <- function(input, output, session) {
output$my_table <- renderDataTable({
df[1:input$nrow,]
})
}
shinyApp(ui, server)
Adding CSS
There are multiple ways to add custom CSS to a Shiny application, as explained here. The preferred way to add CSS to a Shiny application in a reproducible example is to add the CSS in the code, rather than in a separate file. This can be done by adding a line in the ui
of an application, for example as follows:
tags$head(tags$style(HTML('body {background-color: lightblue;}'))),