I am trying to create a NBA shot analysis dashboard and I created 5 variables to sort the data by that update based on their existence in the dataframes from all NBA Teams which I downloaded from NBAsavant.com. so to reproduce this on your machine you should have to just download one teams csv file.
This is done through a selectizeGroupUI and SelectiveGroupServer.
My problem is that when the user selects the restraints to subset the data, I want to pull two columns from that specific subset the user created through the inputs.
That way the final dashboard would show the x and y coordinates in the ggplot based entirely on what the users inputs are, which I am sure of how to code into the ggplot function itself.
Any help would be appreciated!
#
# 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)
library(shinythemes)
library(plotly)
library(tidyverse)
library(rsconnect)
library(readr)
library(ggplot2)
library(plyr)
library(dplyr)
library(jpeg)
library(grid)
library(RCurl)
library(shinyWidgets)
# import all NBA teams csv files into one dataframe
mydir = "NBA Teams 2017-2018"
myfiles = list.files(path = mydir, pattern = "*.csv", full.names = TRUE)
myfiles
data_csv = ldply(myfiles, read_csv)
courtImg <- "http://robslink.com/SAS/democd54/nba_court_dimensions.jpg"
court <- rasterGrob(readJPEG(getURLContent(courtImg)),
width = unit(1, "npc"), height = unit(1, "npc"))
ui = pageWithSidebar(
headerPanel("NBA 2017-2018 Season: Shooting Analysis"),
sidebarPanel(
# uiOutput("team_name"),
# uiOutput("name"),
# uiOutput("shot_type"),
# uiOutput("shot_made_flag"),
# uiOutput("action_type")
selectizeGroupUI(
id = "my-filters",
inline = FALSE,
params = list(
team_name = list(inputId = "team_name", title = "NBA Team", placeholder = 'Select NBA Team'),
name = list(inputId = "name", title = "Player", placeholder = 'Select a Player'),
shot_type = list(inputId = "shot_type", title = "2 PT or 3 PT", placeholder = 'Select Value'),
shot_made_flag = list(inputId = "shot_made_flag", title = "FGA / FG", placeholder = 'Select Between All Shot Attempts or Only Shots Made'),
action_type = list(inputId = "action_type", title = "Shot Type", placeholder = 'Select Shot Type'))
)
),
mainPanel(
#tableOutput("table"),
plotOutput("court_plot")
)
)
server <- function(input, output, session) {
res_mod <- callModule(
module = selectizeGroupServer,
id = "my-filters",
data = data_csv,
vars = c("team_name", "name", "shot_type", "shot_made_flag", "action_type")
)
output$court_plot <- renderPlot({
res_mod()
ggplot(data_csv, aes(x = x, y = colory)) +
annotation_custom(court, -250, 250, -50, 420) +
geom_point(color = data_csv$shot_type) +
xlim(-250, 250) +
ylim(-50, 420)
})
}
shinyApp(ui = ui, server = server)
here is corrected code:
I added data_i = res_mod() to my ggplot and pipelined it through the rest of code in that block.
#
# 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)
library(shinythemes)
library(plotly)
library(tidyverse)
library(rsconnect)
library(readr)
library(ggplot2)
library(plyr)
library(dplyr)
library(jpeg)
library(grid)
library(RCurl)
library(shinyWidgets)
# import all NBA teams csv files into one dataframe
mydir = "NBA Teams 2017-2018"
myfiles = list.files(path = mydir, pattern = "*.csv", full.names = TRUE)
myfiles
# declare csv file
data_csv = ldply(myfiles, read_csv)
# upload image of court for ggplot
courtImg <- "http://robslink.com/SAS/democd54/nba_court_dimensions.jpg"
court <- rasterGrob(readJPEG(getURLContent(courtImg)),
width = unit(1, "npc"), height = unit(1, "npc"))
# ui for shiny dashboard
ui = fluidPage(
# change the theme to be easier on the eyes
theme = shinytheme('darkly'),
# title of shiny app
headerPanel("NBA 2017-2018 Season: Shooting Analysis"),
sidebarPanel(
# create a subset of the data that changes based on user input and narrows down the choices
selectizeGroupUI(
id = "my-filters",
inline = FALSE,
params = list(
team_name = list(inputId = "team_name", title = "NBA Team", placeholder = 'Select NBA Team'),
name = list(inputId = "name", title = "Player", placeholder = 'Select a Player'),
shot_type = list(inputId = "shot_type", title = "2 PT or 3 PT", placeholder = 'Select Value'),
shot_made_flag = list(inputId = "shot_made_flag", title = "Missed(0) or Made(1) Shot", placeholder = 'Select Between All Shot Attempts or Only Shots Made'),
action_type = list(inputId = "action_type", title = "Shot Type", placeholder = 'Select Shot Type'))
),
status = "primary"
),
mainPanel(
# plot the court next to the user input
plotOutput(outputId = "court_plot", width = '800px')
)
)
# server side of the app that allows the user interactions to affect the dataframe
server <- function(input, output, session) {
# allow the custom subset dataframe to be called
res_mod <- callModule(
module = selectizeGroupServer,
id = "my-filters",
data = data_csv,
vars = c("team_name", "name", "shot_type", "shot_made_flag", "action_type")
)
# the code side of the plot that plots the users input by calling the subsetted dataframe
output$court_plot <- renderPlot({
data_i = res_mod()
data_i %>% ggplot(aes(x, y)) +
annotation_custom(court, -250, 250, -50, 420) +
geom_point(color = data_i$shot_type) +
xlim(-250, 250) +
ylim(-50, 420)
})
}
shinyApp(ui = ui, server = server)
Related
I am trying to create a shiny App which stores plotly objects in a list and I want the user to select from the dropdown X number of stocks they want to perform some analysis to. Then I use some function to split the time series into training and testing data.
What I want to do is update the UI so that the user has the option to select a symbol from a new dropdown (next to the plot area) and then it will generate this new plot. (i.e. by filtering the list of plots by the input$symbol2 name.
I am stuck on the plotsList at the very end of the code.
Code and App:
#
# 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)
library(tidyverse)
library(tidyquant)
library(tidymodels)
library(timetk)
library(plotly)
# library(shiny)
# library(shinyWidgets)
# library(shinyjs)
#
# library(tidyverse)
# library(tidyquant)
# library(Deloitte)
# library(gtExtras)
# library(gt)
# library(htmltools)
#
# library(modeltime)
# library(tidymodels)
# library(timetk)
# library(lubridate)
# library(parsnip)
FANG
uniqueSymbols = unique(FANG$symbol)
# Define UI for application that draws a histogram
ui <- fluidPage(
# Application title
titlePanel("List error"),
shinyWidgets::pickerInput(
inputId = "var_to_forecast_CF1",
label = h4("Variable To Predict"),
choices = c("open", "high"),
selected = "open"
),
verbatimTextOutput("formula_to_estimate_1"),
airYearpickerInput(
inputId = "yearly_range",
label = "Select range of years:",
range = TRUE, value = c(Sys.Date()-365*10, Sys.Date())
),
shinyWidgets::pickerInput(
inputId = "symbol",
label = h4("Select symbol"),
choices = uniqueSymbols,
selected = "Total",
multiple = TRUE,
options = list(
size = 3
)
),
actionButton(inputId = "apply", label = "Aplicar", icon = icon("play")),
plotlyOutput("plot")
)
# Define server logic required to draw a histogram
server <- function(input, output) {
formula_to_estimate = reactive({
#formula(paste0(input$var_to_forecast_CF1, "~Periodo", sep = ""))
paste0(input$var_to_forecast_CF1, "~", "close") %>%
as.formula()
})
output$formula_to_estimate_1 = renderText({
deparse(as.formula(formula_to_estimate()))
})
# Compute Assessment period
# compute the "assess" part of the "time_series_split" function:
assessmentDuration = reactive({
(year(input$yearly_range[2]) - year(input$yearly_range[1])) * 12
})
# A list of 2:
data_to_model = eventReactive(input$apply, {
FANG %>%
filter(symbol %in% input$symbol) %>%
split(., .$symbol)
})
splits = eventReactive(input$apply, {
data_to_model() %>%
map(., ~.x %>%
time_series_split(
assess = assessmentDuration(),
#assess = "18 months",
cumulative = TRUE
)
)
})
plotsList = eventReactive({
splits() %>%
map(., ~.x %>%
ggplot(aes(x = Periodo, y = diff_from_base_year), color = "#041e42") +
geom_line(size = 1) +
#facet_wrap(~input$symbol, ncol = 1) +
labs(
x = "Date", y = "r",
title = "my title"
) +
theme_momura() %>%
ggplotly()
)
})
# How can update the UI and filter a single stock to plot?
output$plot = renderPlotly({
plotsList[[!!sym(input$symbol2)]] # STUCK HERE...........
})
}
# Run the application
shinyApp(ui = ui, server = server)
I have an app with a map, dropdown, calendar and line plot (my real app is much bigger but I have simplified as much as I can). The problem with it is that when I modify any of the uicontrol features, the data loading and plotting routines run twice (as evidenced from the print statements). In the full app the plots display a reasonable amount of data so running them twice leads to poor performance.
The app is structured so that I can select 1 of 2 predefined points on the map and it will change the dropdown and graph. A new location can also be selected with the dropdown menu (which in turn updates the map). There is also a checkbox to lock the timeframe and when this is not selected the timeframe gets reset to the extents of the timeseries for the new location.
I have isolated the problem to the updateDateRangeInput that is called in the server.R file (line 35). I can comment this out and the problem goes away, but then I lose the functionality to reset the calendar to the new timeframe. Does anyone know how I can keep that functionality but stop the data loading and plotting code from running twice?
Example app below:
app.R
library(shiny)
library(rsconnect)
source('ui.R')
source('server.R')
ui <- ui_page()
server <- server_page(input, output, session)
shinyApp(ui=ui, server=server)
ui.R
library(shiny)
library(leaflet)
library(dygraphs)
inc_level <- 5
ui_page <- function(){
fluidPage(
titlePanel("TEST APP"),
sidebarLayout(
sidebarPanel(
leafletOutput('region_map'),
selectInput(inputId = "Site",label = "Pick a site",choices = c("A","B"), selected = "A"),
fluidRow(
column(6,
dateRangeInput(inputId = "timeframe",label="Select time range", start ="2015-07-01", end = "2016-07-01")),
column(4,checkboxInput(inputId = "lock_timeframe",label = "Lock Time Range"))
)
),
mainPanel(
tabsetPanel(
tabPanel("Plot 1", dygraphOutput(outputId = "plot1"))
)
)
)
)
}
server.R
library(shiny)
library(ggplot2)
library(dygraphs)
library(xts)
server_page <- function(input, output, session){
# Create Data -------------------------------------------------------------
Y1 <- c(21000, 23400, 26800)
Time1 <- startdate <- as.Date(c('2007-11-1','2008-3-25','2010-3-14'))
Y2 <- c(11000, 11400, 16800)
Time2 <- startdate <- as.Date(c('2001-11-1','2003-3-25','2005-3-14'))
Lat <-c(-39.095980, -39.605823)
Lon <- c(173.887903, 173.824561)
Site <- c("A","B")
# Extract Data -------------------------------------------------------
df1 <- reactive({
print("load data")
if (input$Site=="A"){
df1 <- data.frame(Time1, Y1)
}
else if (input$Site=="B"){
df1 <- data.frame(Time2, Y2)
}
names(df1) <- c("Time","Y")
if (1){ # IF YOU CHANGE THIS TO A 0 FUNCTIONLITY IS LOST BUT PROBLEM GOES AWAY
lockTest <- input$lock_timeframe
if (lockTest==FALSE){
updateDateRangeInput(session, "timeframe",
start = df1$Time[1],
end =df1$Time[length(df1$Time)])
}
}
df1 <- df1[df1$Time >= format(input$timeframe[1]) & df1$Time <= format(input$timeframe[2]),]
validate(need(nrow(df1)!=0, "No Data In Range"))
return(df1)
}) #%>% bindCache(input$Site) # I woudl like to cache based on location to stop reloading of data from file in the full app
# Line Plot --------------------------------------------------------
output$plot1 <- renderDygraph({
print("Plotting")
data <- df1()
data <- xts(x = data$Y, order.by = data$Time)
dyPlt <- dygraph(data,width = 800, height = 400)
})
# Plot Map -----------------------------------------------------
output$region_map <- renderLeaflet({
y <- Lat
x <- Lon
id <- Site
leaflet() %>%
addProviderTiles(providers$OpenStreetMap, options = providerTileOptions(noWrap = TRUE)) %>%
setView(lng = 174.051515, lat = -39.301619, zoom = 8) %>%
addCircleMarkers(lng = x, lat = y ,color="green", radius = 2, layerId = id, label = id,
labelOptions = labelOptions(noHide = F, direction = "bottom",
style = list("color" = "green","border-color" = "rgba(0,0,0,0.5)"))
)
})
# Map Click Behaviour -----------------------------------------------------
#When map is clicked: update map and change dropdown value
observeEvent(input$region_map_marker_click, {
event <- input$region_map_marker_click
updateSelectInput(session,
inputId = "Site",
label = "Pick a site",
choices = Site,
selected = event$id)
})
# Update map when a new site is selected from the dropdown
observeEvent(input$Site, {
update_markers()
})
# Function to redraw markers and highlight the selected location
update_markers <- function(){
y <- Lat
x <- Lon
id <- Site
sitInd <- id == input$Site
leafletProxy("region_map") %>% clearMarkers() %>% addCircleMarkers(lng = x, lat = y ,color="green", radius = 2, layerId = id, label = id,
labelOptions = labelOptions(noHide = F, direction = "bottom",
style = list("color" = "green","border-color" = "rgba(0,0,0,0.5)")),
options = list(zIndex = 200)) %>%
addCircleMarkers(lng = x[sitInd], lat = y[sitInd] ,color="blue", radius = 4, layerId = id[sitInd], label = id[sitInd],
labelOptions = labelOptions(noHide = F, direction = "bottom",
style = list("color" = "blue","border-color" = "rgba(0,0,0,0.5)")),
options = list(zIndex = 300) )
}
}
I am trying to make a reactive plot with radio buttons in shiny. However, after using the reactive expressions I am not able to see any plot.
Here is the reproducible code of the complete app
# Loading libs
library(shiny)
library(shinythemes)
library(ggplot2)
library(mapdata)
library(mapproj)
ui <- fluidPage(theme = shinytheme("cosmo"),
navbarPage("PageTitle",
tabPanel("US-Data-Visualizer",
sidebarPanel(tags$h2("Map Visualizer"), tags$h4("Visualize the counts on US map, state wise"),
radioButtons("radio_option", label = "Select from the following options:",
choices = list("Total Cases" = "state$TOTAL.CASES", "New Cases" = "state$NEW.CASES",
"Active Cases" = "state$ACTIVE.CASES", "Total Deaths" = "state$TOTAL.DEATHS",
"New Deaths" = "state$NEW.DEATHS", "Total Tests" = "state$TOTAL.TESTS"),
selected = "state$TOTAL.CASES")),
mainPanel(plotOutput("us_cases"))))
) #close fluid page
server <- function(input, output){
state <- read.csv("https://raw.githubusercontent.com/spriyansh/ShinyApps/master/datasets/USA_State_Wise_Data.csv", fileEncoding="UTF-8")
us_geo_data <- map_data("county")
reactive_df <- reactive({
us_geo_data <- data.table(us_geo_data)
covid_map <- data.frame(state_names=unique(us_geo_data$region),
values = input$radio_option)
setkey(us_geo_data,region)
covid_map <- data.table(covid_map)
setkey(covid_map,state_names)
map.df <- us_geo_data[covid_map]})
output$us_cases <- renderPlot(
ggplot(reactive_df()$map.df,
aes(x = reactive_df()$map.df$long, y = reactive_df()$map.df$lat,
group = reactive_df()$map.df$group,fill = reactive_df()$covid_map$values)) +
geom_polygon(alpha = 0.8) + coord_map()
)}
shinyApp(ui, server)
Your example is not reproducible because there is no data and no library calls. Please see here and here to know how to make a minimal, reproducible example.
Edit following OP's edit:
The problem is that you try to return different dataframes from reactive_df, which is impossible. You should instead merge covid_map and state_names together, so that all the information you need is in map.df, which is returned by reactive since it is the last action. Then, you can remove the long expressions in ggplot.
There was also a problem with the choices in radioButtons. It is better to only put the column names as choices and then to call filter the data with these column names with state[[input$radio_option]].
Here's your code:
# Loading libs
library(shiny)
library(shinythemes)
library(ggplot2)
library(mapdata)
library(mapproj)
library(data.table)
library(dplyr)
state <- read.csv("https://raw.githubusercontent.com/spriyansh/ShinyApps/master/datasets/USA_State_Wise_Data.csv", fileEncoding = "UTF-8")
us_geo_data <- map_data("county")
ui <- fluidPage(
theme = shinytheme("cosmo"),
navbarPage(
"PageTitle",
tabPanel(
"US-Data-Visualizer",
sidebarPanel(
tags$h2("Map Visualizer"), tags$h4("Visualize the counts on US map, state wise"),
radioButtons("radio_option",
label = "Select from the following options:",
choices = list(
"Total Cases" = "TOTAL.CASES", "New Cases" = "NEW.CASES",
"Active Cases" = "ACTIVE.CASES", "Total Deaths" = "TOTAL.DEATHS",
"New Deaths" = "NEW.DEATHS", "Total Tests" = "TOTAL.TESTS"
),
selected = "TOTAL.CASES"
)
),
mainPanel(plotOutput("us_cases"))
)
)
) # close fluid page
server <- function(input, output) {
reactive_df <- reactive({
us_geo_data <- data.table(us_geo_data)
covid_map <- data.frame(
state_names = unique(us_geo_data$region),
values = state[[input$radio_option]]
)
setkey(us_geo_data, region)
covid_map <- data.table(covid_map)
setkey(covid_map, state_names)
map.df <- dplyr::left_join(us_geo_data, covid_map, by = c("region" = "state_names"))
})
output$us_cases <- renderPlot(
ggplot(
reactive_df(),
aes(
x = long, y = lat,
group = group, fill = values
)
) +
geom_polygon(alpha = 0.8) +
coord_map()
)
}
shinyApp(ui, server)
I am working on an app where the user can upload either one file or multiple files of individual-level data to get analyzed.
So far if the user uploads multiple files the app combines all the files in one dataset and analyzes all of them combined. I have different outputs 2 tables and a graph.
What I am struggling to do is when the user uploads multiple files I want to keep the compiled result but I want to add dynamic tabs to each box according to the number of files uploaded to present the table/graph for that file alone.
I added a checkbox so the user checks it if they are uploading multiple files. The idea was to write an observeEvent code to insert tabs according to the number of files being uploaded, that code got complicated because I had to put the renderTable chunk within it, and it is not working.
So my question is, is there a better way of doing what I am trying to do? and If my idea makes sense what is wrong with my code and why isn't it working? Thank you
Here is a sample of the code;
library(shiny)
library(dplyr)
library(shinydashboard)
library(tidyr)
library(shinyjs)
ui <- dashboardPage(
dashboardHeader(title = "Treatment and Care Cascade",
titleWidth = 300),
#Sidebar contents (tabs)
dashboardSidebar(
sidebarMenu(
menuItem("HIV Cascade", tabName = "hiv")
)),
#Main panel for displaying outputs
dashboardBody(
tabItems(
#First tab content
tabItem(tabName = "hiv",
h2("HIV Treatment and Care Cascade"),
fluidRow(
#Input: Select a file for hcv data
box(fluidRow(
box(fileInput("dt_hiv","Choose CSV File",
multiple = TRUE,
accept = c("text/csv",
"text/comma-separated-values,tesxt/plain",".csv")),width = 12,solidHeader = TRUE, height = 75),
#Input: Checkbox if file has header
box(checkboxInput("multiplehiv", "Uploading multiple files",TRUE),width = 3,solidHeader = TRUE, height = 50)), width = 12, height = 255),
#Outputs
tabBox(id = "hivcasbox", tabPanel(id = "tab1", title ="HIV Cascade",tableOutput("hivcascade"))),
box(tableOutput("hivCascadeduration"), title = "HIV Cascade - duration", solidHeader = TRUE)
))
)))
server <- function(input, output){
#Combining the datasets together
dthiv <- reactive({req(input$dt_hiv)
rbindlist(lapply(input$dt_hiv$datapath, fread, header = input$hivheader, quote = input$hivquote, sep = input$hivsep),
use.names = TRUE, fill = TRUE)
})
#The analysis chunk
cascade_hiv <- reactive({dthiv() %>% summarize("Diagnosed" = sum(hiv_posresult,na.rm = T),
"Linkage to care" = sum(linkagetocare_hiv,na.rm = T))})
cascade_hiv1 <- reactive({as.data.frame(t(cascade_hiv()))})
Percentage <- reactive({(round((cascade_hiv1()$V1*100/cascade_hiv1()$V1[1]),1))})
cascade_hiv3 <- reactive({cbind(cascade_hiv1(),Percentage())})
cascade_hiv4 <- reactive({cascade_hiv3() %>% rename(Total = V1, Percentage = "Percentage()")})
output$hivcascade <- renderTable({
cascade_hiv5 <- as.data.frame(cascade_hiv4())
rownames(cascade_hiv5) <- c("Diagnosed","Linkage to care")
cascade_hiv5},include.rownames = TRUE)
observeEvent(input$multiplehiv, {
for (i in 1:length(input$dt_hiv$datapath)) {
insertTab(inputId = "hivcasbox",
tabPanel(paste("Region",i), renderTable({
dthiv_r <- input$dt_hiv$datapath[i] %>% summarize("Diagnosed" = sum(hiv_posresult,na.rm = T),
"Linkage to care" = sum(linkagetocare_hiv,na.rm = T))
cascade_hiv1_r <- as.data.frame(t(dthiv_r))
Percentage_r <- round((cascade_hiv1_r$V1*100/cascade_hiv1_r$V1[1]),1)
cascade_hiv3_r <- cbind(cascade_hiv1_r,Percentage_r)
cascade_hiv4_r <- cascade_hiv3_r %>% rename(Total = V1, Percentage = "Percentage_r")
cascade_hiv5_r <- as.data.frame(cascade_hiv4_r)
rownames(cascade_hiv5_r) <- c("Diagnosed","Linkage to care")
cascade_hiv5_r},include.rownames = FALSE)),
target = "tab1")
}
})
}
shinyApp(ui, server)
Created on 2019-08-01 by the reprex package (v0.3.0)
the app runs but when I check the multiple files box, no tabs get inserted
I couldn't get the above code to work but I found another one that works using "str and eval(parse(text = str))",
however, it is not the most elegant or concise code, so I would appreciate it if someone has a better way of doing it. Thank you!
ibrary(shiny)
library(dplyr)
library(shinydashboard)
library(tidyr)
library(shinyjs)
library(data.table)
ui <- dashboardPage(
dashboardHeader(title = "Treatment and Care Cascade",
titleWidth = 300),
dashboardSidebar(
sidebarMenu(
menuItem("HIV Cascade", tabName = "hiv")
)),
dashboardBody(
tabItems(
#First tab content
tabItem(tabName = "hiv",
h2("HIV Treatment and Care Cascade"),
fluidRow(
#Input: Select a file for hcv data
box(fluidRow(
box(fileInput("dt_hiv","Choose CSV File",
multiple = TRUE,
accept = c("text/csv",
"text/comma-separated-values,tesxt/plain", ".csv")),width = 12,solidHeader = TRUE, height = 75),
#actionButton("multiplehiv", "Add 'Dynamic' tab"),
#Input: Checkbox if file has header
box(checkboxInput("multiplehiv", "Uploading multiple files",FALSE),
width = 3,solidHeader = TRUE, height = 50)
), width = 12, height = 255),
#Outputs
uiOutput("tabs")
))
)))
server <- function(input, output){
dthiv <- reactive({req(input$dt_hiv)
rbindlist(lapply(input$dt_hiv$datapath, fread),
use.names = TRUE, fill = TRUE)
})
cascade_hiv <- reactive({dthiv() %>% summarize("Diagnosed" = sum(hiv_posresult,na.rm = T),
"Linkage to care" = sum(linkagetocare_hiv,na.rm = T))})
cascade_hiv1 <- reactive({as.data.frame(t(cascade_hiv()))})
Percentage <- reactive({(round((cascade_hiv1()$V1*100/cascade_hiv1()$V1[1]),1))})
cascade_hiv3 <- reactive({cbind(cascade_hiv1(),Percentage())})
cascade_hiv4 <- reactive({cascade_hiv3() %>% rename(Total = V1, Percentage = "Percentage()")})
n_files <- reactive({length(input$dt_hiv$datapath)})
output$tabs <- renderUI({
if (input$multiplehiv == 1) {
str <- "tabBox(id = 'hivcasbox',
tabPanel(id = 'taball', title = 'HIV Cascade' ,tableOutput('hivcascade')),"
for (i in 1:n_files()) {str <- paste0(str, "tabPanel(id = paste('tab', ",i,") , title = paste('Data', ",i,") , tableOutput('hivcascader_",i,"')),")}
str <- gsub(",$",")",str)
eval(parse(text = str))
}
else {
tabBox(id = "hivcasbox",
tabPanel(id = "tab1", title = "HIV Cascade",tableOutput("hivcascade")))
}
})
output$hivcascade <- renderTable({
cascade_hiv5 <- as.data.frame(cascade_hiv4())
rownames(cascade_hiv5) <- c("Diagnosed","Linkage to care")
cascade_hiv5},include.rownames = TRUE)
dt_files <- reactive({lapply(input$dt_hiv$datapath[1:n_files()],read.csv)})
observe({
for (i in 1:n_files())
{str1 <- paste0("dthiv_r_",i,"<- reactive({dt_files()[[",i,"]] %>% summarize('Diagnosed' = sum(hiv_posresult,na.rm = T),
'Linkage to care' = sum(linkagetocare_hiv,na.rm = T))})
cascade_hiv1_r_",i,"<- reactive({as.data.frame(t(dthiv_r_",i,"()))})
Percentage_r_",i,"<- reactive({round((cascade_hiv1_r_",i,"()$V1*100/cascade_hiv1_r_",i,"()$V1[1]),1)})
cascade_hiv3_r_",i," <- reactive({cbind(cascade_hiv1_r_",i,"(),Percentage_r_",i,"())})
cascade_hiv4_r_",i,"<- reactive({cascade_hiv3_r_",i,"() %>% rename(Total = V1, Percentage = 'Percentage_r_",i,"()')})")
eval(parse(text = str1))}
for (i in 1:n_files()) {
str2 <- paste0("output$hivcascader_",i," <- renderTable({
cascade_hiv5_r_",i," <- as.data.frame(cascade_hiv4_r_",i,"())
rownames(cascade_hiv5_r_",i,") <- c('Diagnosed','Linkage to care')
cascade_hiv5_r_",i,"},include.rownames = TRUE)")
eval(parse(text = str2))}
})
}
shinyApp(ui, server)
I am able to take input dates from the user and but can't make it wait to execute after entering the dates.
library(shiny)
library(ggplot2)
library(quantmod)
# Define UI for application that draws a bar graph
ui <- fluidPage(
# Application title
titlePanel("My Plot"),
sidebarLayout(
sidebarPanel(
textInput("text", "Enter company name:", width = NULL,
placeholder = "comp.name"),
dateRangeInput("dates", h3(strong("Date Range")),
start = "2001-01-01", end = Sys.Date(),
min = "0000-01-01", max = Sys.Date(),
format = "dd-mm-yy", separator = strong("to"),
autoclose = TRUE),
submitButton(text = "submit")),
# Show a plot
mainPanel( h1(strong(textOutput("Company"))),
tableOutput("MRF"),
plotOutput("finally")
)
)
)
# Define server logic required to draw a histogram
server <- function(input, output) {
output$MRF <- renderTable({
tyu2 <- getSymbols(input$text , src = "yahoo", verbose = TRUE,
from = min(input$date) , to = max(input$date), auto.assign = FALSE)})
output$finally <- renderPlot({ggplot(data = tyu2 , aes(x= x ,y=tyu))+
geom_bar(stat = "identity", fill = "blue")+
theme(axis.text.x = element_text(angle = 90)) +
xlab("Dates")+ ylab(comp.name)})
}
# Run the application
shinyApp(ui = ui, server = server)
The dates must be going in as infinity which is the default case when the dates are not being read. I am not understanding what is wrong. Could anybody help me out. Thank you