11.15 LOADING THINGS (2)
Code outside
server <- function(input, output) {}
is run once, when you launch your appCode inside
server <- function(input, output) {}
is run once each time a user visits your appCode inside
render*
functions is rerun constantly (not only when user changes widget value, see [reactivity(http://shiny.rstudio.com/articles/understanding-reactivity.html)])That means…
- Load Source scripts, libraries, and data outside of
server
function (at the beginning)- Store data in
www/
folder in your app directory - Access with
read.table("www/swiss.csv", sep=",")
- Access online data by inserting the url into the
read*
function (e.g.read.table()
)
- Store data in
- User specific objects (e.g. object that records user’s session information) are defined inside shinyServer’s unnamed function, but outside of any render* calls
- e.g. user registers himself, user data as input data (compare income)
- Code/objects that are affected by choices in widgets must be placed witin the a
render*
function- Shiny reruns code in a
render*
chunk each time a user changes a widget mentioned in the chunk
- Shiny reruns code in a
- Load Source scripts, libraries, and data outside of
Avoid placing code within render function that does not need to be there… for performance reasons!
Example
data <- read.table("http://paulcbauer.eu/wp-content/uploads/2016/10/swiss.csv", sep=",")
# data <- read.table("data/swiss.csv", sep=",")
ui <- fluidPage(
titlePanel("Displaying reactive output"),
sidebarLayout(
sidebarPanel(
selectInput("selection", label = h3("Select box"),
choices = list("Fertility" = "Fertility",
"Agriculture" = "Agriculture",
"Examination" = "Examination",
"Education" = "Education",
"Catholic" = "Catholic",
"Infant.Mortality" = "Infant.Mortality"), selected = 1)
),
mainPanel(
plotOutput("distPlot"),
textOutput("text1")
)))
server <- function(input, output) {
output$distPlot <- renderPlot({
x <- data[, input$selection]
hist(x, col = 'darkgray', border = 'white', xlab=input$selection, main="Swiss French Provinces Fertility and Socioeconomic Indicators (1888) Data")
})
output$text1 <- renderText({
input$selection
})
}
shinyApp(ui = ui, server = server)