Trying to Build my First Shiny App - r

I came across the video tutorial here.
http://blog.revolutionanalytics.com/2016/03/rtvs-preview.html
Right around minute 24:15 the instructor starts talking about the shiny app that he built. He has it pre-built, and simply runs it, so it's basically impossible for me to figure out how he actually went from nothing to a real working app. I watched a few tutorials on YouTube, and they were helpful to get me up to speed a little, but still can't get this working. As best as I can tell, these are (kind of) the steps, but again, I stil can't get this working.
RStudio > File > New File > Shiny Web App. Then name the app and crate a directory.
Now, I have a template that looks like this.
#
# This is a Shiny web application. You can run the application by clicking
# the 'Run App' button above.
#
# Find out more about building applications with Shiny here:
#
# http://shiny.rstudio.com/
#
library(shiny)
# Define UI for application that draws a histogram
ui <- shinyUI(fluidPage(
# Application title
titlePanel("Old Faithful Geyser Data"),
# Sidebar with a slider input for number of bins
sidebarLayout(
sidebarPanel(
sliderInput("bins",
"Number of bins:",
min = 1,
max = 50,
value = 30)
),
# Show a plot of the generated distribution
mainPanel(
plotOutput("distPlot")
)
)
))
# Define server logic required to draw a histogram
server <- shinyServer(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')
})
})
# Run the application
shinyApp(ui = ui, server = server)
Based on the video, I created a template (with some basic R code). It looks like this.
library(shiny)
library(leaflet)
library(plyr)
ui <- fluidPage(
actionButton("recalc", "New points"),
mainPanel(
tabsetPanel(
tabPanel("Order Locations", leafletOutput("map",width="80%",height="400px")),
tabPanel("Markers", verbatimTextOutput("markers"))
)
)
)
server <- function(input, output, session) {
airports <- read.csv("https://raw.githubusercontent.com/jpatokal/openflights/master/data/airports.dat", header = FALSE)
colnames(airports) <- c("ID", "name", "city", "country", "IATA_FAA", "ICAO", "lat", "lon", "altitude", "timezone", "DST")
countries <- sort(unlist(lapply(unique(airports$country), as.character)))
}
shinyApp(ui, server)
This doesn't do anything at all. Ugh.
I believe the 'ui' is a function that calls arguments form the 'server'. Is that right? Am I close, or way off base? How can I get this working? It seems VERY useful. I'm trying to learn the nuts and bolts of this stuff so I can do it myself. Thank you!

Related

ReferenceError: Can't find variable: Pickr when running shinytest::recordTest()

I am currently working on an RShiny App which became pretty big and hence I want to implement automated UI testing. I therefore tried to record my UI tests with recordTest() from the shinytest package. However, when I run shinytest::recordTest(), I get the error message "ReferenceError: Can't find variable: Pickr" (see attached image). I located the problem to be a colorPickr from the shinyWidgets package and it seems like it has something to do with a .js-File in the package, but I have no idea how to solve this problem.
Error Message
When running shinytest::recordTest(), I usually would expect that the app starts in a headless browser and I can record my tests. This works perfectly fine, when I disable the line of code where the colorPickr is defined. With the colorPickr, the above error occurs.
I tried to update my R version (unfortunately we are working with 3.6.0 currently) and updated all packages, which did not help. I also tried to install phantomJS and set my PATH variable to the phantomjs.exe. Did not help either (not sure if I did that correctly tbh).
The package versions I use are: shinytest_1.5.1, shinyWidgets_0.6.2, shiny_1.6.0
The error is reproducable with the following example app:
library(shiny)
library(shinyWidgets)
library(shinytest)
# Define UI for app that draws a histogram ----
ui <- fluidPage(
# App title ----
titlePanel("Hello Shiny!"),
# Sidebar layout with input and output definitions ----
sidebarLayout(
# Sidebar panel for inputs ----
sidebarPanel(
# Input: Slider for the number of bins ----
sliderInput(inputId = "bins",
label = "Number of bins:",
min = 1,
max = 50,
value = 30),
colorPickr(
inputId = "color",
label = "Pick a color",
selected = "blue" )
),
# Main panel for displaying outputs ----
mainPanel(
# Output: Histogram ----
plotOutput(outputId = "distPlot")
)
)
)
# Define server logic required to draw a histogram ----
server <- function(input, output) {
output$distPlot <- renderPlot({
x <- faithful$waiting
bins <- seq(min(x), max(x), length.out = input$bins + 1)
hist(x, breaks = bins, col = "#007bc2", border = "white",
xlab = "Waiting time to next eruption (in mins)",
main = "Histogram of waiting times")
})
}
shinyApp(ui, server)
To reproduce the error, run shinytest::recordTest().
Thanks in advance for any help!

How can I trigger an output when a value changes in a different output?

I have an output that takes user input to select which of a number of calculations to use and results in 5 numbers. That output pushes out the results of this and other calculations as an HTML table. The individual calculations are not particularly complicated, but user selections choose which of many approaches they are using, so I don't really want to replicate all that code in other outputs that are going to use just those 5 numbers.
My thought was to use the double-arrow to make those numbers available to the other outputs (in my case some plots). My goal is to generate graphs from numbers already generated in a different output, however that gets accomplished. I am not attached to the approach below, it is just where I am right now.
I ran into a number of problems just using <<- and tried a lot of things to get it to work. I won't complicate this further with all the things I tried and the problems they created.
The MRE below replicates this by calculating a number in one output that is then to be used in another output. If you enter different numbers of bins, the second output is never triggered to update to the new number. For this MRE I could of course directly use the user input to calculate that number but that is what I am trying to avoid in the real app. I also don't want to use a "Go!" button if I can avoid it since part of the fun is watching how things change in response to your various selections.
# Define UI for application that draws a histogram
ui <- fluidPage(
# Application title
titlePanel("Old Faithful Geyser Data"),
# Sidebar with a slider input for number of bins
sidebarLayout(
sidebarPanel(
numericInput("bins",
"Number of bins:",
min = 1,
max = 50,
value = 30)
),
# Show a plot of the generated distribution
mainPanel(
plotOutput("distPlot"),
textOutput("binnum")
)
)
)
# Define server logic required to draw a histogram
server <- function(input, output) {
a_number<-0
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)
a_number<<-bins[2]/5}
# draw the histogram with the specified number of bins
hist(x, breaks = bins, col = 'darkgray', border = 'white')
})
output$binnum<-renderText({
a_number
})
}
# Run the application
shinyApp(ui = ui, server = server)
Could you just treat bins and a_number as reactive?
# Define UI for application that draws a histogram
ui <- fluidPage(
# Application title
titlePanel("Old Faithful Geyser Data"),
# Sidebar with a slider input for number of bins
sidebarLayout(
sidebarPanel(
numericInput("bins",
"Number of bins:",
min = 1,
max = 50,
value = 30)
),
# Show a plot of the generated distribution
mainPanel(
plotOutput("distPlot"),
textOutput("binnum")
)
)
)
# Define server logic required to draw a histogram
server <- function(input, output) {
# a_number<-0
# generate bins based on input$bins from ui.R
data(faithful)
x <- faithful[, 2]
bins <- reactive({
seq(min(x), max(x), length.out = input$bins + 1)
})
a_number <- reactive({
req(bins())
-bins()[2]/5
})
output$distPlot <- renderPlot({
# draw the histogram with the specified number of bins
hist(x, breaks = bins(), col = 'darkgray', border = 'white', xlab = paste0("a = ", -bins()[2]/5))
})
output$binnum<-renderText({
a_number()
})
}
# Run the application
shinyApp(ui = ui, server = server)

R Function shinyApp will not run

I absolutely cannot figure out why my shiny app will not run. I'm fairly new to shiny I will mention. I'm running the following code locally, but when I run it, it never completes, just sits there. Any help is GREATLY appreciated. Code is below:
ui <- fluidPage(
# App title ----
titlePanel("Hello World!"),
# Sidebar layout with input and output definitions ----
sidebarLayout(
# Sidebar panel for inputs ----
sidebarPanel(
# Input: Slider for the number of bins ----
sliderInput(inputId = "bins",
label = "Number of bins:",
min = 5,
max = 50,
value = 30)
),
# Main panel for displaying outputs ----
mainPanel(
# Output: Histogram ----
plotOutput(outputId = "distPlot")
)
)
)
# Define server logic required to draw a histogram ----
server <- function(input, output) {
# Histogram of the Old Faithful Geyser Data ----
# with requested number of bins
# This expression that generates a histogram is wrapped in a call
# to renderPlot to indicate that:
#
# 1. It is "reactive" and therefore should be automatically
# re-executed when inputs (input$bins) change
# 2. Its output type is a plot
output$distPlot <- renderPlot({
x <- faithful$waiting
bins <- seq(min(x), max(x), length.out = input$bins + 1)
hist(x, breaks = bins, col = "#75AADB", border = "orange",
xlab = "Waiting time to next eruption (in mins)",
main = "Histogram of waiting times")
})
}
shinyApp(ui = ui, server = server)
Result:
It never completes, just sits there.
Ok, so I figured out the answer to this. It was a permission thing with my company. If anyone runs into this issue in the future, be sure to evaluate your level of internet permissions.

Read R code from a file (i.e. source) in a shiny App

I want to modularise my shiny app code, by moving parts of the code in separate files. I then include the content of the file with a call to the source function: source("./www/some_code.R", local = TRUE)
It works well except for an undesired effect: the word TRUE is added just below the insert.
Could you help me understand why this happen and how I can remove this undesired text?
For a reproducible example,
create app.R:
#
# Find out more about building applications with Shiny here:
#
# http://shiny.rstudio.com/
#
library(shiny)
# Define UI for application that draws a histogram
ui <- fluidPage(
# Application title
titlePanel("Old Faithful Geyser Data"),
# Sidebar with a slider input for number of bins
sidebarLayout(
sidebarPanel(
source("./www/slider.R", local = TRUE)
),
# Show a plot of the generated distribution
mainPanel(
plotOutput("distPlot")
)
)
)
# Define server logic required to draw a histogram
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')
})
}
# Run the application
shinyApp(ui = ui, server = server)
and in the www folder the slider.R:
sliderInput("bins",
"Number of bins:",
min = 1,
max = 50,
value = 30)
Just when I posted this, I saw a link to this which answer the question: displaying TRUE when shiny files are split into different folders
I thought that I did my research though... Should I delete the whole thread?

How to delete a file created by a Shiny app when the ssession closes

I generate and display a flextable in a Shiny app and want to place it in a PDF. The only available method is to convert the flextable object to a PNG then place the PNG in the PDF. For each PNG file I assign a filename including a date-time stamp to make it unique between sessions. This file name is saved in a reactiveValue.
When the user is finished and the session is closed, how can I delete the file? If I do not I will pile up extraneous files. I cannot use onSessionEnded() because the reactive values are all gone when the browser is closed. I cannot generalize using a pattern because other users have files with a similar name. I have to delete these PNG files specifically.
Any ideas?
onSessionEnded code that does not work:
observe({
session$onSessionEnded(function() {
unlink(c(values$fnameSummary))
unlink(c(values$fnameLike))
unlink(c(values$fnameRisk1))
})
})
This produces the following error:
Warning: Error in .getReactiveEnvironment()$currentContext: Operation not
allowed without an active reactive context. (You tried to do something
that can only be done from inside a reactive expression or observer.)
Stack trace (innermost first):
33: .getReactiveEnvironment()$currentContext
32: .subset2(x, "impl")$get
31: $.reactivevalues
30: $
29: unlink
28: callback [C:\Users\jch1748\Documents\Projects\W2017010 - Combined Risk Tool\testing/server.R#2790]
1: runApp
maybe a working example will help?
#
# This is a Shiny web application. You can run the application by clicking
# the 'Run App' button above.
#
# Find out more about building applications with Shiny here:
#
# http://shiny.rstudio.com/
#
library(shiny)
tsts <- reactiveValues()
# Define UI for application that draws a histogram
ui <- fluidPage(
# Application title
titlePanel("Old Faithful Geyser Data"),
# Sidebar with a slider input for number of bins
sidebarLayout(
sidebarPanel(
sliderInput("bins",
"Number of bins:",
min = 1,
max = 50,
value = 30)
),
# Show a plot of the generated distribution
mainPanel(
plotOutput("distPlot")
)
)
)
# Define server logic required to draw a histogram
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')
})
observe({
tsts$fname <- "AAA.txt"
write(input$bins, file=tsts$fname)
})
onSessionEnded(function() {
cat("Session Ended\n")
unlink(tsts$fname)
})
}
# Run the application
shinyApp(ui = ui, server = server)
I had a similar problem where I wanted to dynamically serve images and pdf files for download in a shiny app. Therefore the files need to be placed within the www-directory which makes the use of tempdir impossible. Additionally, the created files needed to be deleted after the app stops. I solved the problem with the following code:
session$onSessionEnded(function() {
system(paste("rm -f", PathToFile))
})
No need to use reactiveValues. Please see:
library(shiny)
# Define UI for application that draws a histogram
ui <- fluidPage(
# Application title
titlePanel("Old Faithful Geyser Data"),
# Sidebar with a slider input for number of bins
sidebarLayout(
sidebarPanel(
sliderInput("bins",
"Number of bins:",
min = 1,
max = 50,
value = 30)
),
# Show a plot of the generated distribution
mainPanel(
plotOutput("distPlot")
)
)
)
# Define server logic required to draw a histogram
server <- function(input, output, session) {
fname <- "AAA.txt"
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')
})
observe({
write(input$bins, file=fname)
})
session$onSessionEnded(function() {
cat("Session Ended\n")
unlink(fname)
})
}
# Run the application
shinyApp(ui = ui, server = server)

Resources