using server outputs as input parameters in Shiny - r

Below you will find some code for a very simple shiny dashboard.
It includes a global list called choice, which has three elements: date.1, date.2 and date.3 (each one is a different date sequence).
The UI includes just three inputs:
One select input which allows the user to select one of our global choices.
One start date input
One end date input.
The server function starts with a reactive expression which creates a vector of our choices selection. Then there are two text outputs which pull the min and max date values of our selection.
What i'm trying to do is use the start.date and end.date outputs to populate the value parameters of the date inputs in the ui, so depending on which choice you select the starting points of the date inputs will change.
library(shiny)
start.date1 <- as.Date("2017-01-01","%Y-%m-%d")
end.date1 <- as.Date("2017-01-31","%Y-%m-%d")
start.date2 <- as.Date("2017-02-01","%Y-%m-%d")
end.date2 <- as.Date("2017-02-28","%Y-%m-%d")
start.date3 <- as.Date("2017-03-01","%Y-%m-%d")
end.date3 <- as.Date("2017-03-31","%Y-%m-%d")
choice <- list()
choice$date.1 <- as.character(seq(start.date1,end.date1,by="week"))
choice$date.2 <- as.character(seq(start.date2,end.date2,by="week"))
choice$date.3 <- as.character(seq(start.date3,end.date3,by="week"))
ui <- fluidPage(
selectInput("select.scenario","select.scenario", choices = names(choice)),
dateInput("start.date","start.date",value = textOutput("start.date")),
dateInput("end.date","end.date",value = textOutput("end.date"))
)
server <- function(input, output) {
dates <- eventReactive(input$select.scenario,{
df <- choice[[as.character(input$select.scenario)]]
})
output$start.date <- renderText({
df <- dates()
start.date <- min(as.Date((df)))
start.date
})
output$end.date <- renderText({
df <- dates()
end.date <- max(as.Date((df)))
end.date
})
}
shinyApp(ui = ui, server = server)

You can't output into the ui definition. Either use uiOutput, or set the values/ranges using the update functions:
library(shiny)
start.date1 <- as.Date("2017-01-01","%Y-%m-%d")
end.date1 <- as.Date("2017-01-31","%Y-%m-%d")
start.date2 <- as.Date("2017-02-01","%Y-%m-%d")
end.date2 <- as.Date("2017-02-28","%Y-%m-%d")
start.date3 <- as.Date("2017-03-01","%Y-%m-%d")
end.date3 <- as.Date("2017-03-31","%Y-%m-%d")
choice <- list()
choice$date.1 <- as.character(seq(start.date1,end.date1,by="week"))
choice$date.2 <- as.character(seq(start.date2,end.date2,by="week"))
choice$date.3 <- as.character(seq(start.date3,end.date3,by="week"))
ui <- fluidPage(
selectInput("select.scenario","select.scenario", choices = names(choice)),
dateInput("start.date","start.date"),
dateInput("end.date","end.date")
)
server <- function(session, input, output) {
dates <- eventReactive(input$select.scenario,{
df <- choice[[as.character(input$select.scenario)]]
})
observeEvent(input$select.scenario, {
updateDateInput(session, "start.date", value=min(as.Date(dates())))
updateDateInput(session, "end.date", value=max(as.Date(dates())))
})
}
shinyApp(ui = ui, server = server)

Related

Filtering 2 tables in R, based on selected choices and displaying graph in a shinny app

I am new to r and shinny, and can't figure out how to fix my code. I have 2 dfs (df and historical), and I filter the df to display results selected from SelectInput (col, and col2, "Market" and "Month"). At the same time, I want to filter historical by the same values choosen for "Market" and "Month", and display below the table, a histogram of the filtered price_vector - that is, "average_price" from "historical" but filtered by chosen "Market" and "Month".
Any feedback is appreciated, and by the way, if you have a solution that uses reticulate, I dont mind it (no problem for me filtering a df using python/pandas, but I am teaching myself shinny and can't figure this out)
library(shiny)
library(reticulate)
df <- read.csv(file = 'scores.csv')
historical <- read.csv('TRAIN.csv')
price_vector <- historical$average_price
lmkt <- unique(df$market)
mth <- unique(df$month)
ui <- fluidPage(
selectInput('col','Market',lmkt),
selectInput('col2','Month',mth),
dataTableOutput('table')
)
server <- function(input,output)
output$table <- renderDataTable({
df <- df
{
df = df[df[["market"]] == input$col,]
df = df[df[["month"]] == input$col2,]
}
})
shinyApp(ui = ui, server = server)
You can combine the two statements into one using & operator.
df <- read.csv('https://raw.githubusercontent.com/lmsanch/pyABS/master/scores.csv')
historical <- read.csv('https://raw.githubusercontent.com/lmsanch/pyABS/master/TRAIN.csv')
price_vector <- historical$average_price
lmkt <- unique(df$market)
mth <- unique(df$month)
ui <- fluidPage(
selectInput('col','Market',lmkt),
selectInput('col2','Month',mth),
dataTableOutput('table'),
plotOutput('plot')
)
server <- function(input,output) {
output$table <- renderDataTable({
df[df$market == input$col & df$month == input$col2, ]
})
output$plot <- renderPlot({
hist(price_vector[df$market == input$col & df$month == input$col2])
})
}
shinyApp(ui, server)

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

R Shiny: Creating New Columns Within a Reactive Data Frame

Say I have a data frame called summarized which includes the columns TY_COMP and LY_COMP (among others). I could write a function in R that performs a calculation on TY_COMP and LY_COMP and creates a new column called cac in the data frame like this:
summarized$cac <- summarized$TY_COMP/summarized$LY_COMP-1
cac is now a new column in the summarized data frame.
Now say that summarized() is a reactive data frame with the same columns.
How could I achieve the effect done in the non-reactive data frame, i.e. create a new column within the current frame? Or how would I get the same effect?
I tried:
summarized$cac <- reactive({summarized()$TY_COMP/summarized()$LY_COMP-1})
I reckon you want to modify a reactive when for example an actionButton is clicked. For this purpose I would use reactiveValues. You can modify reactiveValue inside of observers such as observe or observeEvent.
Check out this simple example:
summarized <- data.frame(id = 1:20, group = letters[1:4], TY_COMP = runif(20), LY_COMP = runif(20))
library(shiny)
ui <- fluidPage(
verbatimTextOutput("text"),
actionButton("btn", "Add the 'cac' column to summarized")
)
server <- function(input, output){
rv <- reactiveValues(summarized = summarized)
output$text <- renderPrint(rv$summarized)
observeEvent(input$btn, {
rv$summarized$cac <- summarized$TY_COMP / summarized$LY_COMP - 1
})
summarized_mod <- reactive({
summarized()$TY_COMP / summarized()$LY_COMP-1
})
}
shinyApp(ui, server)
Another option would be to create another reactive that has an additional column. This is possible to use, but depending on your use case, I recommend the first solution.
Example:
summarized <- data.frame(id = 1:20, group = letters[1:4], TY_COMP = runif(20), LY_COMP = runif(20))
library(shiny)
ui <- fluidPage(
verbatimTextOutput("text1"),
verbatimTextOutput("text2")
)
server <- function(input, output){
output$text1 <- renderPrint(summarized_orig())
output$text2 <- renderPrint(summarized_mod())
summarized_orig <- reactive( {
summarized
})
summarized_mod <- reactive({
df <- summarized_orig()
df$cac <- summarized_orig()$TY_COMP / summarized_orig()$LY_COMP - 1
df
})
}
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)

Formatting selectInput() to show character dates to the user

I am currently building a shiny app and trying to get a set of dates to render as character strings to the end user, while still keeping their date format when invoked in the server side code.
There might be a simple solution here, but unsure how to get the dates to format in the selectInput dropdown. In my actual use case, using a date slider isn't ideal as the dates do not follow a common interval.
Reproducible example below:
# setup
require(lubridate)
test.dates <- as.Date(c('2014-06-01', '2014-07-01', '2014-08-01',
'2014-09-01', '2014-10-01', '2014-11-01',
'2014-12-01', '2015-01-01','2015-02-01',
'2015-03-01', '2015-04-01'))
test.names <- as.character(paste0(month(test.dates, label = T), ' ',
year(test.dates)))
test.df <- data.frame(date = test.dates)
row.names(test.df) <- test.names
# shiny
server <- function(input, output) {
output$table <- renderTable(test.df)
}
ui <- fluidPage(
sidebarLayout(
sidebarPanel(
selectInput("test", label = "DATE FORMAT TEST:", choices =
test.df, selected = test.df[1,])
),
mainPanel(tableOutput('table'))
)
)
shinyApp(ui = ui, server = server)
I believe you will find it much easier to pass around character objects than date objects in Shiny. I would simply use the direct character values of your dates and whenever you need them to be date objects in your subsequent analysis explicitly convert to a date object. The following provides an example where both the dropdown and table have the character formatted dates.
require(lubridate)
myDates <- c('2014-06-01', '2014-07-01', '2014-08-01',
'2014-09-01', '2014-10-01', '2014-11-01',
'2014-12-01', '2015-01-01','2015-02-01',
'2015-03-01', '2015-04-01')
test.names <- as.character(paste0(lubridate::month(test.dates, label=TRUE), ' ',
year(test.dates)))
test.df <- data.frame(date = myDates)
row.names(test.df) <- test.names
# shiny
server <- function(input, output) {
output$table <- renderTable(test.df)
}
ui <- fluidPage(
sidebarLayout(
sidebarPanel(
selectInput("test", label = "DATE FORMAT TEST:", choices =
myDates, selected = myDates[1])
),
mainPanel(tableOutput('table'))
)
)
shinyApp(ui = ui, server = server)

Resources