Change reactive time for dygraph's dyRangeSelector in Shiny - r

I'm building a Shiny application where I want to use the dyRangeSelector from dygraphs to provide the input period.
My problem is that I only want the reactive change to fire when the selector receives a "MouseUp"-event, ie., when the user is done with choosing the period. Right now events are dispatched as the selector is moved which results in a lagged app since the computations done for each period take a few seconds. Essentially, Shiny is too reactive for my taste here (I know this it the wrong way round - normally we want the apps to be super reactive).
Can I modify when the reactive request is dispatched?
Here's a small example that shows the problem.
library(quantmod)
library(shiny)
library(dygraphs)
library(magrittr)
# Create simple user interface
ui <- shinyUI(fluidPage(
sidebarLayout(
sidebarPanel(
dygraphOutput("dygraph")
),
mainPanel(
plotOutput("complicatedPlot")
)
)
))
server <- shinyServer(function(input, output) {
## Read the data once.
dataInput <- reactive({
getSymbols("NASDAQ:GOOG", src = "google",
from = "2017-01-01",
auto.assign = FALSE)
})
## Extract the from and to from the selector
values <- reactiveValues()
observe({
if (!is.null(input$dygraph_date_window)) {
rangewindow <- strftime(input$dygraph_date_window[[1]], "%Y-%m-%d")
from <- rangewindow[1]
to <- rangewindow[2]
} else {
from <- "2017-02-01"
to <- Sys.Date()+1
}
values[["from"]] <- from
values[["to"]] <- to
})
## Render the range selector
output$dygraph <- renderDygraph({
dygraph(dataInput()[,4]) %>% dyRangeSelector() %>% dyOptions(retainDateWindow = TRUE)
})
## Render the "complicated" plot
output$complicatedPlot <- renderPlot({
plot(1,1)
text(1,1, values[["from"]])
Sys.sleep(1) ## Inserted to represent computing time
})
})
## run app
runApp(list(ui=ui, server=server))

There is a function in shiny called debounce which might pretty much suit your needs. If you rewrite the limits to a reactive expression (as opposed to observe), you can wrap it into debounce with a specification of time in milliseconds to wait before evaluation. Here is an example with 1000ms:
library(quantmod)
library(shiny)
library(dygraphs)
library(magrittr)
# Create simple user interface
ui <- shinyUI(fluidPage(
sidebarLayout(
sidebarPanel(
dygraphOutput("dygraph")
),
mainPanel(
plotOutput("complicatedPlot")
)
)
))
server <- shinyServer(function(input, output) {
## Read the data once.
dataInput <- reactive({
getSymbols("NASDAQ:GOOG", src = "google",
from = "2017-01-01",
auto.assign = FALSE)
})
## Extract the from and to from the selector
values <- reactiveValues()
limits <- debounce(reactive({
if (!is.null(input$dygraph_date_window)) {
rangewindow <- strftime(input$dygraph_date_window[[1]], "%Y-%m-%d")
from <- rangewindow[1]
to <- rangewindow[2]
} else {
from <- "2017-02-01"
to <- Sys.Date()+1
}
list(from = from,
to = to)
}), 1000)
## Render the range selector
output$dygraph <- renderDygraph({
dygraph(dataInput()[,4]) %>% dyRangeSelector() %>% dyOptions(retainDateWindow = TRUE)
})
## Render the "complicated" plot
output$complicatedPlot <- renderPlot({
plot(1,1)
text(1,1, limits()[["from"]])
Sys.sleep(1) ## Inserted to represent computing time
})
})
## run app
runApp(list(ui=ui, server=server))
This basically means that the reactive expression must be returning the same value for at least 1s to be send to its dependencies. You can experiment with the best time.

Related

Reduce number of times I call a function dependent on the selectizeInput box

I developed a small shiny app:
app
The app plots the rain for stations that are chosen in the selectizeInput.
It goes to an external server for the data each time a station is add or removed.
At the moment, it fetches the data from an external server for all the stations regardless if they remain in the list or not. This adds time and computation that are not needed.
My question is how do I reduce the need to get data that is already present?
because I can't present the real app I created a reproducible app to illustrate my code flow:
#data
id <- as.numeric(1:26)
names(id) <- letters
#dataframe function
get.rain.data <- function(id){
print(id)
vec <- 1:100
id <- as.numeric(id)
print(id)
df <- do.call(rbind,lapply(id,function(i)
tibble(x=vec,y=vec*i+vec^2*i,
id=as.factor(rep(i,length(vec))))))
return(df)
}
#plot function
plot.rain <- function(df){
print(df)
p <- ggplot(df,aes(x=x,y=y,group=id))+
geom_line(aes(color=id),size=0.6)
ggplotly(p,height=700)
}
#### UI
ui <- fluidPage(
titlePanel(h1("Rain Intensities and Cumulative Rain")),
sidebarLayout(
sidebarPanel(
helpText("Check rain with info from
IMS.gov.il"),
selectizeInput("var", h3("Select station"),
choices = id,
multiple = T,
selected = 4)
),
mainPanel(
plotlyOutput("rain")
)
)
)
# Define server logic ----
server <- function(input, output) {
dataInput <- reactive({
get.rain.data(input$var)
})
output$rain <- renderPlotly({
req(input$var)
plot.rain(dataInput())
})
}
# Run the application
shinyApp(ui = ui, server = server)
You have the needed code. Everywhere you want to use results from input$var call DataInput() instead. By creating the reactive dataInput function, it will be called when the input$var is updated
# Define server logic ----
server <- function(input, output) {
dataInput <- reactive({
get.rain.data(input$var)
})
output$rain <- renderPlotly({
plot.rain(dataInput())
})
}
I think what you need is to cache values so that they are only queried once. You may want look at the memoise package the can automatically do this for you.
https://github.com/r-lib/memoise

Creating new column for reactive dataframe in shiny/shiny dashboard R

within the server for my shinyApp, I created a dataframe based on the inputs. However, I want to add a new column that utilizes two of the columns of that dataframe.
server <- function(input, output, session) {
l.out <- reactive({
BatchGetSymbols(tickers = input$stock,
first.date = Sys.Date() - as.integer(input$length),
last.date = Sys.Date())
})
stock_info <- reactive({
l.out()$df.tickers
})
stock_info()$return <- reactive({
rep(0, length(stock_info()$ref.date))
})
stock_info()$return <- reactive({
for (i in 2:length(stock_info()$ref.date)){
stock_info()$return[i] <- ((stock_info()$price.close[i] -
stock_info()$price.close[i - 1]) / stock_info$price.close[i - 1])
}
})
I have tried it like this, and it works up until I try to create stock_info()$return, where I keep getting the error that NULL left assignment.
Any tips?
I'm not familiar with the BatchGetSymbols package, but the concepts in the example below should be applicable for your use case as well.
First things first, for lack of an elegant way to say this, I'm pretty sure the expression...
stock_info()$return <- reactive({
rep(0, length(stock_info()$ref.date))
})
...just isn't really how shiny reactive objects and the associated syntax work.
It looks like you could simplify your code a lot by condensing a bunch of your intermediate steps into a single expression. If you only have one set of reactive data you will use in all of your outputs, this might be a more straight forward approach.
library(shiny)
ui <- fluidPage(
textInput('stock','stock',"GE"),
sliderInput('length', 'length', min = 1, max = 10, value = 5),
dataTableOutput('my_table')
)
server <- function(input, output, session) {
## This will update whenever either input$length or input$stock change
stock_info <- reactive({
length <- as.integer(input$length)
temp_stock_info <- data.frame(stock = input$stock,
foo = seq_len(length),
bar = rnorm(length))
temp_stock_info$baz <- paste("xxx",length)
return(temp_stock_info)
})
## Return an output
output$my_table <- renderDataTable({
stock_info()
})
}
shinyApp(ui, server)
However, if you are using the intermediate object l.out for a variety of end outputs, it might make sense to make it a reactive object of it's own. Then, we can update l.out whenever a relevant input changes, and then use that intermediate variable to cascade updates through the other downstream reactives.
In addition, we can update downstream reactive objects like stock_info based on other conditions that don't affect l.out without re-running l.out every time.
library(shiny)
ui <- fluidPage(
textInput('stock','stock',"GE"),
sliderInput('length', 'length', min = 1, max = 100, value = 50),
sliderInput('displayLength', 'displayLength', min = 1, max = 20, value = 5),
dataTableOutput('my_table')
)
server <- function(input, output, session) {
## l.out will change with input$length and input$stock
## but NOT input$displayLength
l.out <- reactive({
data.frame(stock = input$stock,
foo = rnorm(input$length),
l.out_update_time = Sys.time())
})
## stock_info will update whenever l.out changes or the displayLength changes.
## l.out will NOT be updated if only input$displayLength changes
stock_info <- reactive({
tmp_stock_info <- head(x = l.out(), n = input$displayLength)
tmp_stock_info$stock_info_update_time <- Sys.time()
return(tmp_stock_info)
})
## Return an output
output$my_table <- renderDataTable({
stock_info()
})
}
shinyApp(ui, server)

How to return multiple values in R ShinyServer

I am doing the following:
using R ShinyUI, get client inputs on ranges of variables A, B, C;
in R ShinyServer, read in a csv file, and using the client inputs to slice the csv, and get the portion that I need;
Perform a loop calculation on the csv, calculate various statistics from the loop output, and plot all these statistics.
Pseudo code:
data = read.csv('file.csv')
shinyServer(function(input, output) {
data <- reactive({
data = data[data$A<INPUT1 & data$B> INPUT2 & data$C<INPUT3,]
})
for (i in 1:dim(data)[1]){
result1[i] = xxx
result2[i] = xxx
}
output$plot <- renderPlot({
plot(result1)
})
})
The above code does not work. I want to know:
How to correctly incorporate user input and get the variable "data,"
How to plot result1 and result2 from output$plot
Thanks!
The for loop should be inside a the renderPlot, so each time the input$month changes, the reactive data will change and then the for lop will update your variables. If you have the for loop outside a reactive expression, it will be executed only once when the app starts, but after changes in the input.
Below is simple example based on the pseudo code you provide in your original question to illustrate the possible solution.
library(shiny)
ui <- shinyUI( fluidPage(
fluidRow(
column(4,
numericInput("input1", "Speed >", 8),
numericInput("input2", "Dist >", 15)
),
column(8,
plotOutput("plot")
)
)
))
server <- shinyServer(function(input, output) {
dat0 <- cars
data <- reactive({
dat0[dat0$speed > input$input1 & dat0$dist > input$input2,]
})
output$plot <- renderPlot({
s <- dim(data())[1]
result1 <- numeric(s)
result2 <- numeric(s)
for (i in 1:s){
result1[i] <- data()[i, 1]
result2[i] <- data()[i, 2]
}
plot(result1, result2)
})
})
shinyApp(ui = ui, server = server)

Shiny Module that calls a reactive data set in parent Shiny server

I'm looking to port some older Shiny apps to use Shiny Modules, but running into trouble trying to port over my reactive expressions.
According to the documentation:
The goal is not to prevent modules from interacting with their
containing apps, but rather, to make these interactions explicit. If a
module needs to use a reactive expression, take the reactive
expression as a function parameter.
I have existing reactive expressions that import data from APIs etc. that I would like to pass in, but can't seem to find the syntax. If I modify the given Shiny module example below I can get to the same problem.
Could anyone modify the below so that you can pass in the car_data() reactive data into the module? I've tried just about every combination of isolate and car_data/car_data() I can think of and am stumped :)
I would prefer to not need to call the data within the module itself, as in my case I'm trying to generalise an ETL function applicable to lots of datasets.
library(shiny)
library(ggplot2)
linkedScatterUI <- function(id) {
ns <- NS(id)
fluidRow(
column(6, plotOutput(ns("plot1"), brush = ns("brush"))),
column(6, plotOutput(ns("plot2"), brush = ns("brush")))
)
}
linkedScatter <- function(input, output, session, data, left, right) {
# Yields the data frame with an additional column "selected_"
# that indicates whether that observation is brushed
dataWithSelection <- reactive({
brushedPoints(data(), input$brush, allRows = TRUE)
})
output$plot1 <- renderPlot({
scatterPlot(dataWithSelection(), left())
})
output$plot2 <- renderPlot({
scatterPlot(dataWithSelection(), right())
})
return(dataWithSelection)
}
scatterPlot <- function(data, cols) {
ggplot(data, aes_string(x = cols[1], y = cols[2])) +
geom_point(aes(color = selected_)) +
scale_color_manual(values = c("black", "#66D65C"), guide = FALSE)
}
ui <- fixedPage(
h2("Module example"),
linkedScatterUI("scatters"),
textOutput("summary")
)
server <- function(input, output, session) {
### My modification
### making the reactive outside of module call
car_data <- reactive({
mpg
})
## This doesn't work
## What is the syntax for being able to call car_data()?
df <- callModule(linkedScatter, "scatters", car_data(),
left = reactive(c("cty", "hwy")),
right = reactive(c("drv", "hwy"))
)
output$summary <- renderText({
sprintf("%d observation(s) selected", nrow(dplyr::filter(df(), selected_)))
})
}
shinyApp(ui, server)
Drop the parens after car_data:
df <- callModule(linkedScatter, "scatters", car_data,
left = reactive(c("cty", "hwy")),
right = reactive(c("drv", "hwy"))
)
The module seems to want "unresolved" reactives. The parentheses "resolves" them.
If you want to pass input which is not part of the module just wrap it around reactive() as stated in a tutorial.
If a module needs to access an input that isn’t part of the module,
the containing app should pass the input value wrapped in a reactive
expression (i.e. reactive(...)):
callModule(myModule, "myModule1", reactive(input$checkbox1))
Update:
As correctly stated in another answer and Joe Cheng correct way to pass reactive expression is without brackets ()
callModule(linkedScatter, "scatters", car_data)
One option is also to modularize your API input function so you don't need to define reactive expression outside modules. Example of modularized input can be found from this answer.
Below your code with right answer.
library(shiny)
library(ggplot2)
linkedScatterUI <- function(id) {
ns <- NS(id)
fluidRow(
column(6, plotOutput(ns("plot1"), brush = ns("brush"))),
column(6, plotOutput(ns("plot2"), brush = ns("brush")))
)
}
linkedScatter <- function(input, output, session, data, left, right) {
# Yields the data frame with an additional column "selected_"
# that indicates whether that observation is brushed
dataWithSelection <- reactive({
brushedPoints(data(), input$brush, allRows = TRUE)
})
output$plot1 <- renderPlot({
scatterPlot(dataWithSelection(), left())
})
output$plot2 <- renderPlot({
scatterPlot(dataWithSelection(), right())
})
return(dataWithSelection)
}
scatterPlot <- function(data, cols) {
ggplot(data, aes_string(x = cols[1], y = cols[2])) +
geom_point(aes(color = selected_)) +
scale_color_manual(values = c("black", "#66D65C"), guide = FALSE)
}
ui <- fixedPage(
h2("Module example"),
linkedScatterUI("scatters"),
textOutput("summary")
)
server <- function(input, output, session) {
data(mpg)
### My modification
### making the reactive outside of module call
car_data <- reactive({
mpg
})
## Fix This doesn't work by reactive (var) no brackets()
## What is the syntax for being able to call car_data()?
df <- callModule(linkedScatter, "scatters", reactive(car_data),
left = reactive(c("cty", "hwy")),
right = reactive(c("drv", "hwy"))
)
output$summary <- renderText({
sprintf("%d observation(s) selected", nrow(dplyr::filter(df(), selected_)))
})
}
shinyApp(ui, server)

Using multiple reactive values

I am trying to create a shiny R application where the user inputs 2 dates: the start date and the end date(assuming that the user will choose either of the dates for a particular week).By choosing the dates the user will be able to see how much he will be selling each item from a list of items next week within those days. I have been provided with data on what percent of total sales happen each day within a week. Using that and using data on sales of each item from past week I have tried to create the app. However I think I am making some error while using the reactive expression. Any help will be greatly appreciated. I have provided the code below.
ui.R
library(shiny)
shinyUI(fluidPage(
sidebarLayout(
sidebarPanel(
dateInput('Start_Date',label = "starting on:",value = Sys.Date())
dateInput('End_Date',label = "Ending on:",value = Sys.Date())
),
mainPanel(
tableoutput("mytable")
)
)
))
server.R
library(shiny)
library(stats)
shinyServer(function(input, output) {
Days<-c("Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday")
Percent_sales_by_day<-c(.10,.14,.14,.14,.14,.17,.17)
Data_days<-data.frame(Days,Percent)
items_sold<-c("A","B","C","D")
sales_last_week<-c("100","200","300","800")
Data_sales<-data.frame(items_sold,sales_last_week)
Day_vector<-reactive({
weekdays(seq(as.Date(input$Start_Date),as.Date(input$End_Date),by = "days"))
})
Daily_split_vector<-reactive({
library(dplyr)
Data_days%>%
filter(Days %in% Day_vector())
Data_days$Percent_sales_by_day
})
Daily_split_value<-reactive({
sum(Daily_split_vector())
})
Forecast<-reactive({
Data_sales%>%
mutate(sales_last_week=sales_last_week* Daily_split_value())
})
output$mytable<-renderTable({
Forecast()
})
})
I'm not 100% clear on your underlying objective, but regardless the code below runs for me. I tried to comment all of the changes I made - they were mostly just minor syntactic errors - but let me know if you would like me to clarify anything.
ui.R:
library(shiny)
##
shinyUI(fluidPage(
sidebarLayout(
sidebarPanel(
dateInput(
'Start_Date',
label = "starting on:",
value = Sys.Date()
), ## added comma
dateInput(
'End_Date',
label = "Ending on:",
value = Sys.Date())
),
mainPanel(
tableOutput("mytable") ## 'tableOutput' not 'tableoutput'
)
)
))
server.R:
library(shiny)
library(dplyr)
options(stringsAsFactors=F) ## try to avoid factors unless you
## specifically need them
##
shinyServer(function(input, output) {
Days <- c(
"Sunday","Monday","Tuesday","Wednesday",
"Thursday","Friday","Saturday")
Percent_sales_by_day <- c(
.10,.14,.14,.14,.14,.17,.17)
Data_days <- data.frame(
Days,
Percent_sales_by_day) ## changed from 'Percent'
items_sold <- c("A","B","C","D")
sales_last_week <- c(
100,200,300,800) ## changed from character (???) to numeric type
Data_sales <- data.frame(
items_sold,
sales_last_week)
Day_vector <- reactive({
weekdays(
seq.Date(
as.Date(input$Start_Date),
as.Date(input$End_Date),
by = "day"))
})
Daily_split_vector <- reactive({
Data_days %>%
filter(Days %in% Day_vector()) %>% ## added pipe
## Data_days$Percent_sales_by_day ## changed this line
select(Percent_sales_by_day) ## to this line
})
Daily_split_value <- reactive({
sum(Daily_split_vector())
})
Forecast <- reactive({
Data_sales%>%
mutate(
sales_last_week=sales_last_week* Daily_split_value())
})
output$mytable <- renderTable({
Forecast()
})
})

Resources