I'm new to shiny and this one has been giving me such a difficult. I tried several suggestions I found to the last reactive but none worked. I am not sure what I am doing wrong.
I tried vis <- reactive({}) and vis %>% bind_shiny() that did not work. Any suggestions will be greatly appreciated.
The ui.R appears but the visualization does not and I do not get an error message
server.R
library(shiny)
library(ggvis)
library(dplyr)
dataS <-read.csv("https://raw.githubusercontent.com/indianspice/IS608/master/Final%20Project/Data/shinydata.csv",
stringsAsFactors = FALSE)
function(input, output, session) {
#Filter breaches
breaches <- reactive({
records <- input$records
minyear <- input$year[1]
maxyear <- input$year[2]
# Apply filters
b <- dataS %>%
filter(
TotalRecords >= records,
Year >= minyear,
Year <= maxyear
) %>%
arrange(records)
#Filter by breach
if (input$breach != "All") {
breach <- paste0("%", input$breach, "%")
b <- b %>% filter(Breach %like% breach)
}
#Filter by company
if (!is.null(input$company) && input$company != "") {
company<- paste0("%", input$director, "%")
b <- b %>% filter(Company %like% company)
}
reactive({
xvar_name <- names(axis_vars)[axis_vars == input$year]
yvar_name <- names(axis_vars)[axis_vars == input$records]
xvar <- prop("x", as.symbol(input$xvar))
yvar <- prop("y", as.symbol(input$yvar))
breaches %>%
ggvis(x=xvar, y=yvar, stroke = ~breach) %>%
layer_points() %>%
add_axis("x", title = xvar_name) %>%
add_axis("y", title = yvar_name) %>%
add_legend("stroke", title = "Breach Type",
values = c("Hacking or Malware",
"Unintended Disclosure",
"Insider",
"Portable Device",
"Stationary Device",
"Unknown",
"Payment Card Fraud",
"Physical Loss")) %>%
scale_nominal("stroke", domain = c("Hacking",
"Unintended",
"Insider",
"Portable",
"Stationary",
"Unknown",
"Payment",
"Physical"),
range = c("red", "orange")) %>%
bind_shiny("ggvis", "ggvis_ui")
})
})
}
ui.R
library(shiny)
library(ggvis)
dataS <- read.csv("https://raw.githubusercontent.com/indianspice/IS608/master/Final%20Project/Data/shinydata.csv",
stringsAsFactors = FALSE)
fluidPage(
titlePanel("Data Breaches in the United States"),
#fluidRow(
column(4,
h4("Filter Data"),
sliderInput("records", "Number of records breached",
min = 10,
max = 1000000,
value = 10000,
step = 500),
sliderInput("year", "Year breach reported",
sep = "",
min = 2005,
max = 2017,
value = c(2007, 2010)),
selectInput("breach", "Type of breach",
c("All",
"Hacking or Malware",
"Unintended Disclosure",
"Insider",
"Portable Device",
"Stationary Device",
"Unknown",
"Payment Card Fraud",
"Physical Loss")),
selectInput("organzation", "Select type of organization",
choices = unique(dataS$TypeofOrganization)),
selectInput("company", "Select company",
choices = unique(dataS$Company)
),
textInput("companyName", "Enter company name")
),
#),
mainPanel(
uiOutput("ggvis_ui"),
ggvisOutput("ggvis")
)
)
Data
Company TypeofBreach TypeofOrganization TotalRecords Year
Bullitt Unintended Disclosure Educational Institutions 676 2009
Roane Portable Device Educational Institutions 14783 2009
Halifax Portable Device Healthcare Medical Provider 33000 2009
Suffolk Unintended Disclosure Educational Institutions 300 2009
Penrose Physical Loss Healthcare Medical Providers 175 2009
You are defining a reactive inside a reactive, which is bad. You should define your reactive (changing) data breaches using reactive - that's fine. Then, you should observe changes of that data using observe:
observe({
breaches() ... <do something>
...
%>% bind_shiny("ggvis", "ggvis_ui")
})
and then, at the end, use bind_shiny. See the following minimal example for an introduction how to do it (inspired by ggvis help pages):
library(shiny)
runApp(list(
ui = fluidPage(
sliderInput("slider", "Select rows from mtcars to consider", min=1, max = nrow(mtcars), step = 1, value = c(1,10)),
ggvisOutput("p"),
uiOutput("p_ui")
),
server = function(input, output) {
# define the data according to some input
data <- reactive({
mtcars[ input$slider[1] : input$slider[2], ]
})
# observe changes in the data and update ggvis plot accordingly
observe({
data %>%
ggvis(~wt, ~mpg) %>%
layer_points() %>%
bind_shiny("p", "p_ui")
})
}
))
Related
I have a dataset on which I want to apply 3 filters (City, Type and Name of Universities) consecutively. I want to apply a sequential filtering such that when I choose a specific City, other select inputs (Type and Name of universities) be updated accordingly.
I have tried many variations also through stackoverflow solution, however, unable to come up with a solution.
library(shiny)
library(shinythemes)
library(dplyr)
library(tidyr)
library(readxl)
data <- read_excel("foreign_students_by_nationality_2021_2022.xlsx")
colnames(data) <- c("name", "type", "city", "country", "male", "female", "total")
data$male <- as.numeric(data$male)
data$female <- as.numeric(data$female)
data$total <- as.numeric(data$total)
print(str(data))
# Define UI for application that draws a histogram
ui <- fluidPage(
# Application title
titlePanel("Foreign Students in Turkish Universities"),
theme = shinythemes::shinytheme("superhero"),
# Sidebar with a slider input for number of bins
sidebarLayout(
sidebarPanel(
selectInput("uni_city",
"Select a City",
choices = data$city %>% unique() %>% sort()
),
selectInput("uni_type",
"Select a University Type",
choices = ""
),
selectInput("uni_name",
"Select a University",
choices = ""
)
),
mainPanel(
plotOutput("barplot")
)
)
)
# Define server logic required to draw a histogram
server <- function(input, output, session) {
type_var <- reactive({data %>% filter(city == input$uni_city) %>%
select(type) %>% unique()})
observe({
updateSelectInput(session, "uni_type", choices = type_var())
})
name_var <- reactive({data %>% filter(city == input$uni_city, type == input$uni_type) %>%
select(name) %>% unique() %>% sort()})
observe({
updateSelectInput(session, "uni_name", choices = name_var())
})
output$barplot <- renderPlot({
highest_country <-
data %>%
filter(city == input$uni_city,
type == input$uni_type,
name == input$uni_name) %>%
group_by(country) %>%
summarise(female = sum(female),
male = sum(male),
total = sum(total)) %>%
arrange(desc(total)) %>%
pivot_longer(c(-country, -total), names_to = "gender", values_to = "value") %>%
slice_max(total, n = 20)
ggplot(highest_country,
aes(x = reorder(country, total),
y = value,
fill = gender)
) +
geom_col() +
coord_flip() +
labs(x = "Nationality", y = "Number of Students")
})
}
# Run the application
shinyApp(ui = ui, server = server)
I have been trying to make an app using R Shiny modules. This is what the module looks like.
library(shiny)
library(dplyr)
library(tidyr)
library(plotly)
library(shinycssloaders)
library(lubridate)
library(shinyWidgets)
graphModuleUI <- function(id, itemlist) {
ns <- NS(id)
tagList(
sidebarLayout(
sidebarPanel(
dateRangeInput( ns("daterange"), " Select Date Range",
min = min(dat$Date),
max = max(dat$Date),
start = max(dat$Date) - days(30),
end = max(dat$Date)),
pickerInput(ns("location"),"Select Location",
choices= unique(dat$location),
options = list(`actions-box` = TRUE),multiple = T,
selected = unique(dat$location)),
selectInput(ns("items"), "Select Items", choices = itemlist,
selected = itemlist, multiple= T)
),
mainPanel(
withSpinner(plotlyOutput("plot"))
)
)
)
}
graphModule <- function(input, output, session, data) {
df <- reactive({
data%>%
filter(Date <= input$daterange[2], Date >= input$daterange[1])%>%
filter(location %in% input$location)%>%
filter(item %in% input$items)%>%
group_by(Date)%>%
summarise(avgprice=mean(price))%>%
mutate(pricelag=lag(avgprice,1))%>%
mutate(percent_change=(avgprice-pricelag)/pricelag)
})
output$plot<- renderPlotly({
df()%>%
plot_ly(x=~Date, y=~percent_change, type = 'scatter', mode='lines')%>%
layout(yaxis=list(title="Daily change in %"),
title= paste("Daily change in average price of", input$categories ,"items", sep = " "),
paper_bgcolor='transparent',
plot_bgcolor='transparent')
})
}
The data is as follows
dat<-read.csv("https://docs.google.com/spreadsheets/d/e/2PACX-1vTiN0zQUwFH4neKMbsxBJOpv0Q_OPZkI5mUZXtf45O9mEM_brIFVGPWoXkoNRrzNSKakOsNXO9bdOwO/pub?output=csv")
dat$shop<-as.factor(dat$shop)
dat$category<-as.factor(dat$category)
dat$location<-as.factor(dat$location)
dat$Date<-ymd(dat$Date)
groceries_data <- filter(dat, category == "Groceries")
eat_out_data <- filter(dat, category == "Eating_Out")
wearables_data <- filter(dat, category == "Wearables")
space_data <- filter(dat, category == "Space")
utilities_data <- filter(dat, category == "Utilities")
transport_data <- filter(dat, category == "Transport")
all_data_items<-unique(dat$item)
groceries_data_items<-unique(groceries_data$item)
eat_out_data_items<-unique(eat_out_data$item)
wearables_data_items<-unique(wearables_data$item)
space_data_items<-unique(space_data$item)
utilities_data_items<-unique(utilities_data$item)
transport_data_items<-unique(transport_data$item)
And the app looks like this.
ui <- fluidPage(
titlePanel("PriceTrack"),
tabsetPanel(id = "Prices",
tabPanel("All", graphModuleUI("all", all_data_items)),
tabPanel("Groceries", graphModuleUI("groceries", groceries_data_items)),
tabPanel("Eating Out", graphModuleUI("eating_out", eat_out_data_items)),
tabPanel("Wearables", graphModuleUI("wearables", wearables_data_items)),
tabPanel("Space", graphModuleUI("space", space_data_items)),
tabPanel("Utilities", graphModuleUI("utilities", utilities_data_items)),
tabPanel("Transport", graphModuleUI("transport", transport_data_items))
)
)
server <- function(input, output, session) {
callModule(graphModule, "all", dat)
callModule(graphModule, "groceries", groceries_data)
callModule(graphModule, "eating_out", eat_out_data)
callModule(graphModule, "wearables", wearables_data)
callModule(graphModule, "space", space_data)
callModule(graphModule, "utilities", utilities_data)
callModule(graphModule, "transport", transport_data)
}
# Run the application
shinyApp(ui = ui, server = server)
The modular UI (inputs) work fine. But the plot never renders from the modular server.
I am unable to understand why. It doesn't show any error. Just, the 'spinner' spins for unlimited amount of time.
Can anyone please help me resolve this issue?
Thanks in advance.
I'm creating a shiny app where a user can select a state parent_location and a county name from two drop downs. They can also select a variable of interest layer which will then produce a summary statistics table. I've got my code working up to this point.
What I need to do is select other similar counties (contained in the cluster column) and then display summary statistics for this county as well. I can't seem to figure out how to A) display multiple summary statistics tables and B) dynamically create a list of similar counties.
Code that works
library(shiny)
library(tidyverse)
library(lubridate)
eviction_county_2010 <- read.csv("./eviction_county_2010.csv")
ui <- fluidPage(
sliderInput(inputId = "year",
label = "Select a Year:",
min = 2010,
max = 2016,
value = 2010,
step = 1),
radioButtons(inputId = "layer",
label = "Select a Dataset to View:",
choices = c("Eviction Filing Rate"="eviction_filing_rate", "Percent Rent Burden"="rent_burden",
"Percent Renter Occupied"="pct_renter_occupied", "Poverty Rate"="poverty_rate")),
selectInput(inputId = "state",
label = "Select a State:",
eviction_county_2010$parent_location),
selectInput(inputId = "county",
label = "Select a County:",
choices = NULL),
mainPanel(
h2("Summary of the variable"),
verbatimTextOutput("sum")
)
)
server <- function(input, output, session) {
observe({
x <- filter(eviction_county_2010,parent_location == input$state) %>%
select(name)
updateSelectInput(session,"county","Select a County:",choices = unique(x))}
)
output$sum <- renderPrint({
ec <- eviction_county_2010 %>%
filter(parent_location == input$state) %>%
filter(name == input$county)
summary(ec[,input$layer])
})
}
# Run the application
shinyApp(ui = ui, server = server)
Code I've attempted for displaying for similar counties. It returns 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.) I'm not sure which part needs to be placed inside a reactive expression.
ui <- fluidPage(
sliderInput(inputId = "year",
label = "Select a Year:",
min = 2010,
max = 2016,
value = 2010,
step = 1),
radioButtons(inputId = "layer",
label = "Select a Dataset to View:",
choices = c("Eviction Filing Rate"="eviction_filing_rate", "Percent Rent Burden"="rent_burden",
"Percent Renter Occupied"="pct_renter_occupied", "Poverty Rate"="poverty_rate")),
selectInput(inputId = "state",
label = "Select a State:",
eviction_county_2010$parent_location),
selectInput(inputId = "county",
label = "Select a County:",
choices = NULL),
mainPanel(
h2("Summary of the variable"),
verbatimTextOutput("sum")
)
)
server <- function(input, output, session) {
ec <- eviction_county_2010 %>%
filter(parent_location == input$state) %>%
filter(name == input$county)
sel_clust <- unique(ec$cluster)
sim_cty <- eviction_county_2010[ sample(which(eviction_county_2010$cluster == sel_clust), 4),]
sim_cty <- unique(sim_cty$GEOID)
sim_cty <- append(sim_cty, unique(ec$GEOID))
observe({
x <- filter(eviction_county_2010,parent_location == input$state) %>%
select(name)
updateSelectInput(session,"county","Select a County:",choices = unique(x))}
)
output$sum <- renderPrint({
df1 <- eviction_county_2010 %>%
filter(GEOID == sim_cty[1])
df2 <- eviction_county_2010 %>%
filter(GEOID == sim_cty[2])
df3 <- eviction_county_2010 %>%
filter(GEOID == sim_cty[3])
df4 <- eviction_county_2010 %>%
filter(GEOID == sim_cty[4])
df5 <- eviction_county_2010 %>%
filter(GEOID == sim_cty[5])
summary(df1[,input$layer])
summary(df2[,input$layer])
summary(df3[,input$layer])
summary(df4[,input$layer])
summary(df5[,input$layer])
})
}
# Run the application
shinyApp(ui = ui, server = server)
Is this even possible? What am I doing wrong here?
Move this section:
ec <- eviction_county_2010 %>%
filter(parent_location == input$state) %>%
filter(name == input$county)
sel_clust <- unique(ec$cluster)
sim_cty <- eviction_county_2010[ sample(which(eviction_county_2010$cluster == sel_clust), 4),]
sim_cty <- unique(sim_cty$GEOID)
sim_cty <- append(sim_cty, unique(ec$GEOID))
To a reactive({}) statement. I think that's where your error is.
For example:
ec <- reactive({
eviction_county_2010 %>%
filter(parent_location == input$state) %>%
filter(name == input$county)
sel_clust <- unique(ec$cluster)
sim_cty <- eviction_county_2010[ sample(which(eviction_county_2010$cluster == sel_clust), 4),]
sim_cty <- unique(sim_cty$GEOID)
sim_cty <- append(sim_cty, unique(ec$GEOID))
})
Then later in your sever code use:
ec() %>%
...stuff...
I have a shiny app and within that app, I have a table that I render based on input from the user. Within that pipe on eviction_county_2010 I am attempting to return the table with only a sample of counties in the same cluster as input$county. I figured out how to do this with multiple lines of code and reassignments, but shiny throws an error whenever I do this as it clearly isn't allowed. How can I tweak my code to return this within one pipe?
Code with multiple assignments. When I attempted this, I got 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.)
server <- function(input, output, session) {
ec <- eviction_county_2010 %>%
filter(parent_location == input$state) %>%
filter(name == input$county)
sel_clust <- c(unique(ec$cluster))
sel_geoid <- c(unique(ec$GEOID))
sim_cty <- eviction_county_2010 %>% filter(cluster == sel_clust | GEOID != sel_geoid)
sim_cty <- unique(sim_cty$GEOID)
sim_cty <- sample(sim_cty, 5)
sim_cty <- append(sel_geoid, sim_cty)
...
output$table <- renderTable({eviction_county_2010 %>% filter(GEOID %in% sim_cty)})
I attempted the above code in a reactive, and got Error: 'match' requires vector arguments.
sim_cty <- reactive({ec <- eviction_county_2010 %>%
filter(parent_location == input$state) %>%
filter(name == input$county)
sel_clust <- c(unique(ec$cluster))
sel_geoid <- c(unique(ec$GEOID))
sim_cty <- eviction_county_2010 %>% filter(cluster == sel_clust | GEOID != sel_geoid)
sim_cty <- unique(sim_cty$GEOID)
sim_cty <- sample(sim_cty, 5)
sim_cty <- append(sel_geoid, sim_cty)})
output$table <- renderTable(
eviction_county_2010 %>%
filter(GEOID %in% sim_cty)
Current code
library(shiny)
library(tidyverse)
library(datasets)
library(lubridate)
library(stringr)
eviction_county_2010 <- read.csv("./eviction_county_2010.csv")
ui <- fluidPage(
sliderInput(inputId = "year",
label = "Select a Year:",
min = 2010,
max = 2016,
value = 2010,
step = 1),
radioButtons(inputId = "layer",
label = "Select a Dataset to View:",
choices = c("Eviction Filing Rate"="eviction_filing_rate", "Percent Rent Burden"="rent_burden",
"Percent Renter Occupied"="pct_renter_occupied", "Poverty Rate"="poverty_rate")),
selectInput(inputId = "state",
label = "Select a State:",
eviction_county_2010$parent_location),
selectInput(inputId = "county",
label = "Select a County:",
choices = NULL),
mainPanel(
h2("Comparisons Across Similar Counties"),
tableOutput('table')
)
)
server <- function(input, output, session) {
observe({
x <- filter(eviction_county_2010,parent_location == input$state) %>%
select(name)
updateSelectInput(session,"county","Select a County:",choices = unique(x))}
)
output$table <- renderTable(
eviction_county_2010 %>%
group_by(County) %>%
summarise_at(c("GEOID", "population", "cluster", "poverty_rate", "unemployment_rate", "pct_renter_occupied",
"Percent_Rural", "median_gross_rent", "median_household_income",
"median_property_value", "rent_burden", "pct_white", "pct_nonwhite",
"pct_af_am", "pct_hispanic", "pct_am_ind", "pct_asian",
"pct_nh_pi", "pct_multiple", "pct_other"), mean, na.rm = TRUE) %>%
rename(Population = population, `Poverty Rate` = poverty_rate,
`Unemployment Rate` = unemployment_rate, `% Renter Occupied` = pct_renter_occupied,
`% Rural` = Percent_Rural, `Median Gross Rent` = median_gross_rent, `Median Household Income` = median_household_income,
`Median Property Value` = median_property_value, `Rent Burden` = rent_burden,
`% White` = pct_white, `% Non White` = pct_nonwhite,
`% African American` = pct_af_am, `% Hispanic` = pct_hispanic, `% American Indian` = pct_am_ind,
`% Asian` = pct_asian,
`% Native Hawaiian/Pacific Islander` = pct_nh_pi, `% Multiple` = pct_multiple, `% Other` = pct_other) # %>%
# filter(County == str_c(input$county, input$state, sep = ", "))
)
}
# Run the application
shinyApp(ui = ui, server = server)
I can't test it without an example/toy data (see here to learn how to create one).
But, per your code, when you convert sim_cty to reactive, you need to call it as a function sim_cty():
output$table <- renderTable(
eviction_county_2010 %>%
filter(GEOID %in% sim_cty())
See here to learn more about reactives in shiny.
I'm trying to produce a Shiny app with Leaflet that renders a choropleth map based on different input criteria. The map displays incidents of different types (input$type) and backgrounds (input$background). When additional types or backgrounds are specified, polygons are filled with updated incident data. It is working correctly with one snag. When I switch the date input from date range (input$dateInput) to presidential period (input$president), the choropleth for presidential period renders once, displaying polygons with no data, and then again with the polygons filled with the correct data for the pre-selected period ("President1"). How do I avoid the map rendering twice like this when the Presidency tab is pressed?
Question also listed here on RStudio Community.
The raw data and shapefile used can be accessed here: https://github.com/cjbarrie/shiny_egy.
Working example:
Name of raw data: wikiraw
Name of shapefile: shapefile
Global:
library(shiny)
library(shinydashboard)
library(shinythemes)
library(leaflet)
library(rgdal)
library(rmapshaper)
library(sp)
library(dplyr)
library(lubridate)
wikiraw <-read.csv("~/wikisample_SO.csv")
shapefile <- readOGR("~/EGY_adm2.shp")
shapefile<-spTransform(shapefile, CRS("+init=epsg:4326"))
## Simplify shapefile to speed up rendering
shapefile <- ms_simplify(shapefile, keep = 0.01, keep_shapes = TRUE)
wikbounds<-bbox(shapefile)
wikiraw$incident_date <- as.Date(wikiraw$incident_date,
format = "%m/%d/%Y")
wikiraw$presidency <- rep(NA, nrow(wikiraw))
wikiraw$incident_date1 <- as.numeric(wikiraw$incident_date)
wikiraw$event <- rep(1,nrow(wikiraw))
## Generate presidency categorical var.
wikiraw$presidency <- cut(wikiraw$incident_date1,
breaks = c(-Inf, 15016, 15521, 15889, 16229, Inf),
labels = c("President1", "President2", "President3", "President4", "President5"),
right = FALSE)
Snippet of data.frame wikiraw:
ID_2 incident_date incident_background incident_type presidency event
1 168 2013-11-26 Cultural Group President4 1
2 133 2013-11-29 Cultural Group President4 1
3 137 2014-01-25 Cultural Group President4 1
4 168 2011-01-28 Cultural Collective President1 1
5 168 2016-04-25 Cultural Group President5 1
6 163 2015-02-08 Political Individual President5 1
UI:
ui <- dashboardPage(
dashboardHeader(title = "Map tool"),
dashboardSidebar(sidebarMenu(menuItem("Map", tabName = "map"),
selectInput("input_type", "Date input type",
c("Date", "Presidency")),
uiOutput("dateSelect"),
uiOutput("typeSelect"),
uiOutput("backgroundSelect"),
uiOutput("presidentSelect"))),
dashboardBody(tabItems(
tabItem(tabName = "map",
leafletOutput("mymap", height=500)))))
Server:
server <- function(input, output, session) {
output$dateSelect <- renderUI({
switch(input$input_type,
"Date" = dateRangeInput("dateInput", "Dates:",
min=min(wikiraw$incident_date), max = max(wikiraw$incident_date),
start = min(wikiraw$incident_date), end = max(wikiraw$incident_date)),
"Presidency" = checkboxGroupInput("president", "Presidency",
choices = levels(wikiraw$presidency),
selected = "President1"))
})
output$typeSelect <- renderUI({
selectInput("type", "Incident type",
choices = unique(wikiraw$incident_type), multiple = TRUE,
selected = wikiraw$incident_type[1])})
output$backgroundSelect <- renderUI({
checkboxGroupInput("background", "Incident background",
choices = unique(wikiraw$incident_background),
selected = wikiraw$incident_background[1])})
selected <- reactive({
wikiagg <- wikiraw %>% group_by(ID_2, incident_date, incident_type, incident_background, presidency) %>%
summarize(sum_event = sum(event))
if(input$input_type=="Date"){wikiagg <- filter(wikiagg,
incident_date >= min(input$dateInput),
incident_date <= max(input$dateInput),
incident_type%in%input$type,
incident_background%in%input$background)}
if(input$input_type=="Presidency"){wikiagg <- filter(wikiagg,
incident_type%in%input$type,
incident_background%in%input$background,
presidency%in%input$president)}
wikiagg <- wikiagg %>% group_by(ID_2) %>%
summarize(sum_event = sum(sum_event))
wikiagg
})
output$mymap <- renderLeaflet({
leaflet() %>%
addTiles() %>%
setView(mean(wikbounds[1,]),
mean(wikbounds[2,]),
zoom=6
)
})
observe({
if(!is.null(input$dateInput)){
shapefile#data <- left_join(shapefile#data, selected(), by="ID_2")
##Define palette across range of data
wikiaggpal <- wikiraw %>% group_by(ID_2) %>%
summarize(sum_event = sum(event))
pal <- colorBin("YlOrRd", wikiaggpal$sum_event, bins=5, na.color = "#bdbdbd")
leafletProxy("mymap", data = shapefile) %>%
addTiles() %>%
clearShapes() %>%
addPolygons(data = shapefile, fillColor = ~pal(sum_event), fillOpacity = 0.7,
color = "white", weight = 2)
}})
}
shinyApp(ui, server)
Gif of issue:
https://imgur.com/a/FnfOGKi
Any help would be hugely appreciated!
What if you change the reactive to a reactiveValue and assign the data in an observe? I don't know if it is working correctly as I dont know which shapes & colors to expect, but I am not seeing that double rendering anymore.
(Data & Preparation from question is used)
library(shiny)
library(shinydashboard)
library(shinythemes)
library(leaflet)
library(rgdal)
library(rmapshaper)
library(sp)
library(dplyr)
library(lubridate)
ui <- dashboardPage(
dashboardHeader(title = "Map tool"),
dashboardSidebar(sidebarMenu(menuItem("Map", tabName = "map"),
selectInput("input_type", "Date input type",
c("Date", "Presidency")),
uiOutput("dateSelect"),
uiOutput("typeSelect"),
uiOutput("backgroundSelect"),
uiOutput("presidentSelect"))),
dashboardBody(tabItems(
tabItem(tabName = "map",
leafletOutput("mymap", height=500)))))
server <- function(input, output, session) {
output$dateSelect <- renderUI({
switch(input$input_type,
"Date" = dateRangeInput("dateInput", "Dates:",
min=min(wikiraw$incident_date), max = max(wikiraw$incident_date),
start = min(wikiraw$incident_date), end = max(wikiraw$incident_date)),
"Presidency" = checkboxGroupInput("president", "Presidency",
choices = levels(wikiraw$presidency),
selected = "President1"))
})
output$typeSelect <- renderUI({
selectInput("type", "Incident type",
choices = unique(wikiraw$incident_type), multiple = TRUE,
selected = wikiraw$incident_type[1])})
output$backgroundSelect <- renderUI({
checkboxGroupInput("background", "Incident background",
choices = unique(wikiraw$incident_background),
selected = wikiraw$incident_background[1])})
sel_reactval = reactiveValues(s = NULL)
# selected <- reactive({
observe({
wikiagg <- wikiraw %>% group_by(ID_2, incident_date, incident_type, incident_background, presidency) %>%
summarize(sum_event = sum(event))
if(input$input_type=="Date"){wikiagg <- filter(wikiagg,
incident_date >= min(input$dateInput),
incident_date <= max(input$dateInput),
incident_type%in%input$type,
incident_background%in%input$background)}
if(input$input_type=="Presidency"){wikiagg <- filter(wikiagg,
incident_type%in%input$type,
incident_background%in%input$background,
presidency%in%input$president)}
wikiagg <- wikiagg %>% group_by(ID_2) %>%
summarize(sum_event = sum(sum_event))
sel_reactval$s = wikiagg
# wikiagg
})
output$mymap <- renderLeaflet({
leaflet() %>%
addTiles() %>%
setView(mean(wikbounds[1,]),
mean(wikbounds[2,]),
zoom=6
)
})
observe({
req(!is.null(input$dateInput))
req(nrow(as.data.frame(sel_reactval$s))!=0)
# if(!is.null(input$dateInput)){
# shapefile#data <- left_join(shapefile#data, selected(), by="ID_2")
shapefile#data <- left_join(shapefile#data, sel_reactval$s, by="ID_2")
##Define palette across range of data
wikiaggpal <- wikiraw %>% group_by(ID_2) %>%
summarize(sum_event = sum(event))
pal <- colorBin("YlOrRd", wikiaggpal$sum_event, bins=5, na.color = "#bdbdbd")
leafletProxy("mymap") %>%
addTiles() %>%
clearShapes() %>%
addPolygons(data = shapefile, fillColor = ~pal(sum_event), fillOpacity = 1,
color = "white", weight = 2)
# }
})
}
shinyApp(ui, server)