Error with dates and reactive inputs in R Shiny - r

I am putting together a small R Shiny app which will take several inputs from the user and use these inputs to subset a data frame and provide back two histograms. The users will pick a baseball season, two teams and then this information will provide a reactive list of possible games played between these two teams. The user will then pick a date/game and then a histogram will be displayed for each team which will show the distribution of runs scored per game for each team for all games within that season up to the date/game selected. I feel like I am almost there, I just need to get this date thing sorted out. Right now with the code as is, everything evaluates but I get this error twice;
Warning: Error in eval: do not know how to convert 'input$dates' to class “Date”
and this error twice;
Warning in eval(substitute(expr), envir, enclos) :
Incompatible methods ("Ops.factor", "Ops.Date") for "<"
ui.R
library(shiny)
library(dplyr)
shinyUI(fluidPage(
# Application title
titlePanel("Predicting the winner of a Major League Baseball game"),
sidebarLayout(
sidebarPanel(
selectInput("season","1. Select an MLB Season",
choices = list(2012,2013,2014,2015),
selected = 2012),
selectInput("var_1","2. Select the first team",
choices = c("ARI","ATL","BAL","BOS","CHC","CHW","CIN","CLE","COL","DET",
"HOU","KCR","LAA","LAD","MIA","MIL","MIN","NYM","NYY","OAK",
"PHI","PIT","SDP","SFG","SEA","STL","TBR","TEX","TOR","WSN"),
selected = "BAL"),
selectInput("var_2","3. Select the second team",
choices = c("ARI","ATL","BAL","BOS","CHC","CHW","CIN","CLE","COL","DET",
"HOU","KCR","LAA","LAD","MIA","MIL","MIN","NYM","NYY","OAK",
"PHI","PIT","SDP","SFG","SEA","STL","TBR","TEX","TOR","WSN"),
selected = "BOS"),
uiOutput("dates"),
sliderInput("bins",
"Binwidth:",
min = 1,
max = 5,
value = 2)
),
#main panel
mainPanel(
plotOutput("first_team_hist"),
plotOutput("second_team_hist")
)
)))
server.R
library(shiny)
library(dplyr)
library(ggplot2)
shinyServer(
function(input, output) {
mydf <- read.csv("batting_game_logs_merged.csv")
inputData_1 <- reactive({
filter(mydf,team == input$var_1 & season == input$season & date < as.Date(input$dates,format = "%Y-%m-%d"))
})
inputData_2 <- reactive({
filter(mydf,team == input$var_2 & season == input$season & date < as.Date(input$dates,format = "%Y-%m-%d"))
})
output$dates <- renderUI({
dates = mydf %>% filter(team == input$var_1 & opponent_team == input$var_2 & season == input$season) %>% select(date)
selectInput("dates","Pick a Game Date", as.character(dates[[1]]))
})
output$first_team_hist <- renderPlot({
myplot_1 <- ggplot(inputData_1(), aes(x = team_batting_gamelogs.R)) +
geom_histogram(aes(y = ..density..),
binwidth = input$bins, fill = I("blue"),col = I("red")) +
labs(title = paste("Runs Scored per game for",input$var_1),
x= "Runs Scored per Game", y = "Density")
print(myplot_1)
})
output$second_team_hist<- renderPlot({
myplot_2 <- ggplot(inputData_2(), aes(x = team_batting_gamelogs.R)) +
geom_histogram(aes(y = ..density..),
binwidth = input$bins, fill = I("blue"),col = I("red")) +
labs(title = paste("Runs Scored per game for",input$var_2),
x= "Runs Scored per Game", y = "Density")
print(myplot_2)
})
}
)
Thank you in advance for taking the time to review my problem.
-Josh

I am guessing your problem is the initial NULL value of your input$dates. Your reactive environments inputData_1/2 respond as soon as your UI is rendered (and they get their selected value). But no value has been assigned to input$dates yet, so your first run of these functions gets a NULL. Confirm that as.Date(NULL) yields exactly your error.
I advice you to make your reactive environments only listen to input$dates, i.e.
inputData_1 <- eventReactive(input$dates, {
filter(mydf,team == input$var_1 & season == input$season & date < as.Date(input$dates,format = "%Y-%m-%d"))
})
inputData_2 <- eventReactive(input$dates, {
filter(mydf,team == input$var_2 & season == input$season & date < as.Date(input$dates,format = "%Y-%m-%d"))
})
As far as I can see, you want computations to start only after inserting a date anyway.
Other possible fixes are to isolate the other variables or just add an if(!is.null(input$dates)){ ... } clause to handle NULL input.

Related

Map plot won't show in Shiny app, no error shown

I am fairly new to R Shiny and I've been working on an app with an interactive world map which shows each country's performance at the Olympics, using scale_fill_gradient. The app user gets to choose the performance indicator (total medals won, gold only, weighted score) and the year (1996 to 2020).
The problem is there's no more error shown, but the plot doesn't show either! I have tried to run the functions as normal R script and they worked fine there (the plot showed up in the viewer pane). I found a few others who have also run into problems with no plot or error showing, but their cases are different to mine (e.g. mismatch in Output and Render) so the resolutions don't work for me.
It's a massive dataset so I've not included it here, I thought I might check first if the error could be spotted from the code alone. Here's what I've used:
function
world_map1 <- function(WorldMap, year, performance) {
w_plot1 <- WorldMap %>%
filter(Year == year) %>%
select("long", "lat", "group", "region", all_of(performance)) %>%
replace(is.na(.), 0) %>%
rename_at(performance, ~ "Value") %>%
mutate(Value = as.numeric(as.character(Value)))
tooltip_css <- "background-color:#2E2E2E; font-family: Calibri; color:#F2F2F2;"
w_g1 <- ggplot() +
geom_polygon_interactive(data = subset(w_plot1, lat >= -60 & lat <= 90),
aes(x = long,
y = lat,
fill = Value,
group = group,
tooltip = sprintf("%s<br/>%s", region, Value))) +
scale_fill_gradient(name = "Medals /Score",
low = "lightgoldenrodyellow",
high = "goldenrod1",
na.value = "white")
return(
girafe(
ggobj = w_g1,
options = list(
opts_tooltip(
css = tooltip_css
)
))
)
}
ui
ui <- fluidPage(
titlePanel("Title"),
sidebarLayout(
sidebarPanel(
radioButtons(inputId = "performance", label = "Performance measure:",
choices = c("Total medals won" = "Total",
"Gold medals won" = "Gold",
"Weighted points system" = "Weighted"
)),
width = 3
),
mainPanel(
girafeOutput("mapPlot1"),
sliderInput(inputId = "year", label = "Year:",
min = 1996, max = 2020, step = 4, value = 1996, ticks = FALSE, sep = ""
)
)
)
)
server
server <- function(input, output) {
output$mapPlot1 <- renderGirafe({
ggiraph(code = print(world_map1(WorldMap, input$year, input$performance)))
}
)
}
run app
shinyApp(ui = ui, server = server)
Any help or insights appreciated!
I thought it was my theme() block so I removed that, as shown above. Also checked other cases on no plot showing here, couldn't find one with fixes that would work for me because it seems the underlying problem is different?

How to fix "Error in UseMethod("select") : no applicable method for 'select' applied to an object of class "function""?

I am trying to create an interactive map in R with the covid-19 prison data in the U.S. dataset given (after tidying), trying to plot a map of different variables (ex. staff cases, prisoner cases, prisoner deaths) and having a slider for the different months out of 15 months.
A sample of my dataset for one of the 50 states is seen here:
Sample set
Below is my code so far, and I am quite stuck on everything from asterisk divider and below. I keep getting an error message saying that Error in UseMethod("select") : no applicable method for 'select' applied to an object of class "function" when I try to use select within the created function STATE, though I don't know if that function is correct at all with what I am trying to do.
Any help would mean the world.
if (!require(Lahman)) install.packages('Lahman')
if (!require(plotly)) install.packages('plotly')
if (!require(shiny)) install.packages('shiny')
if (!require(tidyverse)) install.packages('tidyverse')
library(albersusa)
library(shiny)
library(Lahman)
library(tidyverse)
library(plotly)
my_map_theme <- function(){
theme(panel.background=element_blank(),
axis.text=element_blank(),
axis.ticks=element_blank(),
axis.title=element_blank())
}
# Load Dataset from CSV, Dataset saved and tidied from Github
cpc <- read_csv("cpc.csv")
us_states <- usa_sf("laea")
cpc_tidy <- cpc %>%
select(name,
staff_tests,
total_staff_cases,
total_staff_deaths,
prisoner_tests,
total_prisoner_cases,
total_prisoner_deaths,
as_of_date,
year,
Month) %>%
arrange(name)
cpc_tidy_f <- cpc_tidy %>%
group_by(name, year, Month) %>%
summarise(across(everything(), last))
cpc_sel <- cpc_tidy_f
cpc_sel$merge <- as.character.Date(paste(cpc_sel$year, cpc_sel$Month, sep = "-"))
TEST_JOIN <- left_join(us_states, cpc_sel, c=("name"="name"))
*****************************************************
STATE <- function(stat, Month = 11, data = cpc_sel) {
my_stat <- enquo(stat)
data %>%
select(name, merge, plot_stat = !!my_stat) %>%
# filter(yearID >= 1901) %>%
group_by(name, merge) %>%
summarize(plot_stat = sum(plot_stat)) %>%
ungroup() %>%
group_by(merge) %>%
top_n(n_players, wt = plot_stat)
}
COVID_Plot <- function(data) {
p <- TEST_JOIN %>%
mutate(text_y = paste("<b>",name,
"</b>\n Total Variable:",
signif(plot_stat,3),
"in 2020-2021")) %>%
ggplot(cpc_sel) +
geom_sf(aes(fill=plot_stat, text=text_y), color="black") +
scale_fill_continuous("Total of Variable:", low="#EEFBE5", high="#082573") +
my_map_theme()
ggplotly(p, tooltip = "text") %>%
style(hoveron = "fill")
}
# Define user interface (UI) for our app
ui <- fluidPage(
# Application title
titlePanel("Covid-19 Data in prisons across the United States"),
# Sidebar with a slider input for number of bins
sidebarLayout(
sidebarPanel(
selectInput("my_stat",
"Statistic to Plot:",
choices = list("Total Staff Cases" = "tota_staff_cases",
"Total Prisoner Cases" = "tota_prisoner_cases"
),
selected = "tota_prisoner_cases"),
sliderInput("n",
"Months:",
min = 1,
max = 15,
value = 11)),
# Show our plot
mainPanel(
h3(textOutput("TitleText")),
h5(textOutput("SubtitleText")),
h5("Graphs for U.S. prison covid data not implemented yet."),
plotlyOutput("statPlot"),
h5("Data source:",
tags$a(href="https://github.com/themarshallproject/COVID_prison_data/blob/master/data/covid_prison_cases.csv/",
"The Marshall Project Covid Prison Data")),
h5("Graphs inspired by plots in The Marshall Project article, ",
tags$a(href="https://www.themarshallproject.org/2020/05/01/a-state-by-state-look-at-coronavirus-in-prisons/",
"\"A State-By-State Look at 15 Months of Coronavirus in Prisons\""))
)
)
)
# Define server logic required to create the graph
server <- function(input, output) {
output$TitleText <- renderText(paste(input$my_stat, "Records over time"))
output$SubtitleText <- renderText(paste("Graph shows", input$n,
"for each state across the U.S."))
output$statPlot <- renderPlotly({
COVID_Plot(STATE(stat = input$my_stat, Month = input$n,
data = cpc_sel))
})
}
# Run the application
shinyApp(ui = ui, server = server)

"Error in match: 'match' requires vector arguments in R Shiny

I am trying to create a dashboard using R Shiny from NYC Tree Census 2015. The dashboard should look something like in the picture here > Dashboard in Shiny Picture
My code is mentioned below:
library(shiny)
library(tidyverse)
library(ggplot2)
my_data <- read.csv("/Users/abhikpaul/Documents/Documents/Github/Fiverr/2015_Street_Tree_Census_-_Tree_Data.csv")
ui <- fluidPage(
titlePanel("The Dashboard of Tree Distribution in New York City"),
sidebarLayout(
sidebarPanel(
# Description ----
helpText("In this page you can get information about the tree distribution, status, health conditions, and species rank in New York City. Please choose the borough that you want to check. It may take 10 seconds for the graphics to load. Thank you for your patience!"),
#Input: Check boxes for Boroughs ----
checkboxGroupInput("checkboxInput",
label = "Borough",
choices = list("Bronx",
"Brooklyn",
"Manhattan",
"Queens",
"Staten Island"),
selected = "Bronx"),
),
# Main panel for displaying outputs ----
mainPanel(
# Tabs panel for displaying outputs ----
tabsetPanel(type = "tabs",
#Output: About ----
tabPanel("About",
h3("About this dataset", align = "left"),
p("The dataset displays the information of trees (including health, status, species, etc.) within the five boroughs in New York City. The dataset is organized by NYC parks & Recreation and partner organizations."),
h3("How to make NYC an urban forest?", align = "left"),
p("As a group, we are concerned about planting tree and green environments. Therefore, we will focus on identifying the locations that require more taking care of trees, the top species that have the most number of trees in each borough, the health conditions of those species, and the distribution of trees in each borough."),
HTML("<p>For more information, visit: <a href='https://data.cityofnewyork.us/Environment/2015-Street-Tree-Census-Tree-Data/uvpi-gqnh'>2015 NYC Tree Census</a></p>")
),
#Output: Status ----
tabPanel("Status", plotOutput(outputId = "statusplot")),
)
)
)
)
)
server <- function(input, output) {
my_data <- as_tibble(my_data)
my_data <- my_data[my_data$borough %in% checkboxInput,]
my_data <- data.frame(table(my_data$borough,my_data$status))
my_data <- my_data[apply(my_data!=0, 1, all),]
my_data <- my_data %>%
group_by(Var1) %>%
mutate(Percent = (Freq/sum(Freq) * 100))
output$statusplot <- renderPlot({
ggplot(my_data, aes(fill = Var2, y = Percent, x = Var1)) +
geom_bar(position = "dodge", stat = "identity")
})
}
shinyApp(ui = ui, server = server)
However, while running the app, I am getting an error as mentioned below
Warning: Error in match: 'match' requires vector arguments 50: %in% 47: server [/Users/abhikpaul/Documents/Documents/GitHub/Fiverr/my_app.R#90]Error in match(x, table, nomatch = 0L) : 'match' requires vector arguments
Can someone help me fix this issue as I am a newbie in R Shiny?
Try this
server <- function(input, output) {
output$statusplot <- renderPlot({
my_data <- as_tibble(my_data)
my_data <- my_data[my_data$borough %in% input$checkboxInput,]
my_data <- data.frame(table(my_data$borough,my_data$status))
my_data <- my_data[apply(my_data!=0, 1, all),]
my_data <- my_data %>%
group_by(Var1) %>%
mutate(Percent = (Freq/sum(Freq) * 100))
ggplot(my_data, aes(fill = Var2, y = Percent, x = Var1)) +
geom_bar(position = "dodge", stat = "identity")
})
}

Shiny Dashboard Date Slider Input

I am new to R and Shiny and have a problem that I have not been able to solve for hours.
I have a dataset from which I display the daily consumption of coffee on a dashboard, which works very well. The plot is a ggplot geom_line chart.
But now I want to be able to change the time period with two sliders.
The sliders I have also managed to do, but the plot does not change when the slider is moved.
I also suspect that I have an error with the date format.
What am I doing wrong?
Thanks for the help
RawData Dataset
library(shiny)
library(dplyr)
library(data.table)
library(ggplot2)
ui <- shinyUI(fluidPage(
# Application title
titlePanel("Coffee consumption"),
# Sidebar with a slider input for the number of bins
sidebarLayout(
sidebarPanel(
sliderInput("DatesMerge",
"Dates:",
min = as.Date("2018-01-22","%Y-%m-%d"),
max = as.Date("2020-04-04","%Y-%m-%d"),
value= c(as.Date("2018-01-22","%Y-%m-%d"),as.Date("2020-04-04","%Y-%m-%d")),
timeFormat="%Y-%m-%d")
),
mainPanel(
plotOutput("plot_daycount"),
tableOutput("structure"),
tableOutput("rawdata"),
tableOutput("dayconsumption"))
)
)
)
# RawData import
coffeedata = fread("C:/temp/ProductList.csv")
setDF(coffeedata)
coffeedata$Date = as.Date(coffeedata$Date, "%d.%m.%Y")
# Products a day counter
countcoffee <- function(timeStamps) {
Dates <- as.Date(strftime(coffeedata$Date, "%Y-%m-%d"))
allDates <- seq(from = min(Dates), to = max(Dates), by = "day")
coffee.count <- sapply(allDates, FUN = function(X) sum(Dates == X))
data.frame(day = allDates, coffee.count = coffee.count)}
# Making a DF with day consumption
daylicounter = countcoffee(df$coffee.date)
server <- shinyServer(function(input, output) {
output$structure = renderPrint({
str(coffeedata)
})
# Raw Data
output$rawdata = renderTable({
head(coffeedata)
})
output$dayconsumption = renderTable({
head(daylicounter)
})
# GGPLOT2
output$plot_daycount = renderPlot({
DatesMerge = input$DatesMerge
ggplot(daylicounter[daylicounter == DatesMerge], aes(daylicounter$day, daylicounter$coffee.count)) +
geom_line(color = "orange", size = 1)
scale_x_date(breaks = "3 month",
date_labels = "%d-%m-%Y")
# Try outs
# ggplot(daylicounter[month(day) == month(DatesMerge)], mapping = aes(day = day)) +
# geom_line(color = "orange", size = 1)
# scale_x_date(breaks = "3 month",
# date_labels = "%d-%m-%Y")
})
})
shinyApp(ui, server)
I appreciate your help
As noted by #Kevin, you need to use input$DatesMerge[1] and input$DatesMerge[2] when subsetting your data. For clarity, this can be done in a separate step. Try something like this in your server:
output$plot_daycount = renderPlot({
DatesMerge <- as.Date(input$DatesMerge, format = "%Y-%m-%d")
sub_data <- subset(daylicounter, day >= DatesMerge[1] & day <= DatesMerge[2])
ggplot(sub_data, aes(x = day, y = coffee.count)) +
geom_line(color = "orange", size = 1) +
scale_x_date(breaks = "3 month", date_labels = "%d-%m-%Y")
})
Edit Additional question from OP was asked:
Why does my date format look normal with str(coffeedata) but with
head(coffeedata) the date is just a number?
renderTable uses xtable which may have trouble with dates. You can get your dates to display correctly by converting to character first (one option):
output$rawdata = renderTable({
coffeedata$Date <- as.character(coffeedata$Date)
head(coffeedata)
})
output$dayconsumption = renderTable({
daylicounter$day <- as.character(daylicounter$day)
head(daylicounter)
})
See other questions on this topic:
as.Date returns number when working with Shiny
R shiny different output between renderTable and renderDataTable
Welcome to R and Shiny, you are off to a great start. Few things:
I don't recommend you using = in shiny, majority of the cases you want to use <-
To simplify code, no reason to add a variable like DatesMerge. It adds no value (at least in the code above)
For a dual slider, you need to tell shiny which end to pick. input$DatesMerge doesn't mean anything but input$DatesMerge[1] does.
When asking for help, it is always better to add a subset of data within the code itself. You tend to get more help and it is easier to run for the person trying to help (like me I was too lazy to download the file and place it in a folder so I didn't run it)
You need to account for a range of dates in your slider when subsetting the data; you also for the , when subsetting the data.
ggplot(daylicounter[daylicounter %in% input$DatesMerge[1]:input$DatesMerge[2],], aes(daylicounter$day, daylicounter$coffee.count)) +
geom_line(color = "orange", size = 1) +
scale_x_date(breaks = "3 month",
date_labels = "%d-%m-%Y")

Shiny: Conditional Panel and Conditional List of checkboxGroupInput

I want to create a shiny app for plotting the most recent pollstR charts of US presidential primaries. Users should be able to select a Party (Dem or Rep), the Candidates and the states, where the primaries (or Caucusus) took place.
I have three problems:
Based on the selected party (Dem or Rep), users should get the next checkboxGroupInput, where only the Democratic or Republican candidates appear. I try to solved that with a conditionalPanel. However, I cannot use "Candidate" twice as a name for the Widget (later in the server.R I need input$Candidate). How can I solve that?
Based on the selected party (again Dem or Rep), users should get a list of all states, where primaries and caucusus took place up to now. At the moment, I am listing all US states, which I defined before (and hence I get errors, if I want to plot the results of states, where no polls are available). Is there a way to get the list of states from the dataset, which is generated in the server.R part (it is called polls$state there, but I cannot use it, because the ui.R does not now "polls").
I plot the results as bar-charts with ggplot and the facet_wrap function (with two columns). The more states I choose, the smaller the plots get. Is there a way to set the height of the plots and insert a vertical scrollbar in the main panel?
Here is the code for the UI:
shinyUI(fluidPage(
titlePanel("2016 Presidential primaries"),
sidebarLayout(position = "right",
sidebarPanel(
helpText("Choose between Democratic (Dem) and Republican (Rep)
Primaries and Caucuses:"),
selectInput("party",
label = "Dem or Rep?",
choices = c("Dem", "Rep",
selected = "Dem")),
conditionalPanel(
condition = "input.party == 'Dem'",
checkboxGroupInput("Candidate", label = h4("Democratic Candidates"),
choices = list("Clinton" = "Clinton", "Sanders" = "Sanders"),
selected = NULL)),
conditionalPanel(
condition = "input.party == 'Rep'",
checkboxGroupInput("Candidate", label = h4("Republican Candidates"),
choices = list("Bush" = "Bush", "Carson" = "Carson", "Christie" = "Christie",
"Cruz" = "Cruz", "Kasich" = "Kasich", "Rubio" = "Rubio",
"Trump" = "Trump"),
selected = NULL)),
checkboxGroupInput("state",
label = "Select State",
choices = states,
inline = TRUE,
selected = NULL)
),
mainPanel(
tabsetPanel(
tabPanel("Plot", plotOutput("plot")),
tabPanel("Table", tableOutput("table"))
)
)
)
))
And here the code for the server.R:
### getting and cleaning the data for the shiny app-----------------------------
# load pollstR-package to get Huffpost opinion polls
require(pollstR)
# load dplyr and tidyr for data wrangling
require(dplyr)
require(tidyr)
# load ggplot2 for plotting
require(ggplot2)
# download 2016 GOP presidential primaries
repPoll <- pollstr_charts(topic='2016-president-gop-primary', showall = TRUE)
# extract and combine columns needed
choice <- repPoll$estimates$choice
value <- repPoll$estimates$value
election <- repPoll$estimates$slug
party <- repPoll$estimates$party
rep.df <- data_frame(election, choice, value, party)
# extract and combine slug and state info to add list of US state abbreviations
election <- repPoll$charts$slug
state <- repPoll$charts$state
r.stateAbb <- data_frame(election, state)
# join both data frames based on slug
rep.df <- left_join(rep.df, r.stateAbb, by = "election")
## download 2016 DEM presidential primaries
demPoll <- pollstr_charts(topic='2016-president-dem-primary', showall = TRUE)
# extract and combine columns needed
choice <- demPoll$estimates$choice
value <- demPoll$estimates$value
election <- demPoll$estimates$slug
party <- demPoll$estimates$party
dem.df <- data_frame(election, choice, value, party)
# extract and combine slug and state info to add list of US state abbreviations
election <- demPoll$charts$slug
state <- demPoll$charts$state
d.stateAbb <- data_frame(election, state)
# join both data frames based on slug
dem.df <- left_join(dem.df, d.stateAbb, by = "election")
# combine dem and rep datasets
polls <- bind_rows(dem.df, rep.df)
polls$party <- as.factor(polls$party)
polls$state <- as.factor(polls$state)
polls$choice <- as.factor(polls$choice)
shinyServer(function(input, output) {
df <- reactive({
polls %>% filter(party %in% input$party) %>% filter(choice %in% input$Candidate) %>%
filter(state %in% input$state)
})
# generate figures
output$plot <- renderPlot({
validate(
need(input$party, "Please select a party"),
need(input$Candidate, "Please choose at least one candidate"),
need(input$state, "Please select at least one state")
)
p <- ggplot(df())
p <- p + geom_bar(aes(x = choice, weight = value, fill = choice),
position = "dodge", width=.5)
# colorize bars based on parties
if (input$party == "Dem")
p <- p + scale_fill_brewer(palette = "Blues", direction = -1)
if (input$party == "Rep")
p <- p + scale_fill_brewer(palette = "Reds", direction = -1)
# add hlines for waffle-design
p <- p + geom_hline(yintercept=seq(0, 100, by = 10), col = 'white') +
geom_text(aes(label = value, x = choice, y = value + 1), position = position_dodge(width=0.9), vjust=-0.25) +
# facet display
facet_wrap( ~ state, ncol = 2) +
# scale of y-axis
ylim(0, 100) +
# delete labels of x- and y-axis
xlab("") + ylab("") +
# blank background and now grids and legend
theme(panel.grid.major.x = element_blank(), panel.grid.major.y = element_blank(),
panel.grid.minor.y = element_blank(),
panel.background = element_blank(), legend.position = "none")
print(p)
}
)
# Generate a table view of the data
output$table <- renderTable({
polls %>% filter(party %in% input$party) %>% filter(choice %in% input$Candidate) %>%
filter(state %in% input$state)
})
}
)
Here is the solution for problem 1 and 2:
In ui.R, replace conditionalPanel and checkboxGroupInput with
uiOutput('candidates'),
uiOutput('states')
In server.R, add the following code before df <- reactive({..... Note that you need to change some of your input$Candidate code to lower case.
observeEvent(input$party, {
output$candidates <- renderUI({
checkboxGroupInput(
"candidate",
ifelse(input$party == 'Dem', "Democratic Candidates", "Republican Candidates"),
as.vector(unique(filter(polls,party==input$party)$choice))
)
})
})
observeEvent(input$candidate, {
output$states <- renderUI({
states_list <- as.vector(unique(filter(polls, party==input$party & choice==input$candidate)$state))
checkboxGroupInput(
"state",
"Select state",
# Excluding national surveys
states_list[states_list!="US"]
)
})
})
For problem 3, change the df reactive to observe, and then set plot height depending on how many states selected. Also change this line p <- ggplot(df)
observe({
df <- polls %>% filter(party %in% input$party) %>% filter(choice %in% input$candidate) %>% filter(state %in% input$state)
height <- ceiling(length(input$state) / 2) * 200
output$plot <- renderPlot({
#Your plot code
}, height=height)
})

Resources