I am trying to select multiple values from a column on MySQL and Shiny.
Some names with special characters do not return values when queried from a Mysql database.
How can I choose the names but pass to the query the geo instead of the names.
library(shiny)
library(dplyr)
library(sqldf)
library(DT)
library(stringr)
survey <- data.frame("name" = c("Oberösterreich", "Северозападен", "Κύπρος", "Strední Cechy",
"Severovýchod", "Praha"),
"geo" = c("AT31", "BG31", "CY00", " CZ02", "CZ05", "CZ01"),
"population" =c(100409314, 54086980, 30961705, 164741605, 156857074, 93166890))
shinyApp(
ui = fluidPage(
fluidRow(
wellPanel(
selectizeInput(
'Region',
label = "Region Select",
choices = NULL,
options = list(
placeholder = 'Select Region',
maxOptions = 1000,
maxItems = 10,
searchConjunction = 'and'
)
))),
fluidRow(DT::dataTableOutput('table')),
),
server = function(input, output, session){
updateSelectizeInput(session,
"Region",
server = TRUE,
choices = survey$`name`)
geonamesdata <- reactive({
SelectedRegion <-
stringr::str_c(stringr::str_c("'", input$Region, "'"), collapse = ',')
sqldf(paste0("
SELECT DISTINCT c.name, c.geo
FROM survey c
WHERE c.name IN (",
SelectedRegion,
")
"))
})
output$table <- DT::renderDataTable(geonamesdata(),
selection = 'single',
options = list(searching = FALSE,pageLength = 10),
server = FALSE, escape = FALSE,rownames= FALSE)
})
EDIT
I have come up with another demo to illustrate what I would want.
I have a MySQL database but for purposes of this question I will use SQLDF which is similar in syntax on Shiny environment.
library(shiny)
library(dplyr)
library(sqldf)
library(DT)
library(stringr)
df <- data.frame(empName = c("Jon", "Bill", "Maria"),
empID = c("J111", "B222", "M333"),
empAge = c(23, 41, 32),
empSalary = c(21000, 23400, 26800)
)
shinyApp(
ui = fluidPage(
selectizeInput("Search", label = p("Select name"),
choices = as.character(df$empName),
multiple = TRUE),
hr(),
fluidRow(
column(6, DT::dataTableOutput("table1")),
column(6, DT::dataTableOutput("table2"))),
hr(),
hr(),
fluidRow(
column(6, DT::dataTableOutput("table3")),
column(6, DT::dataTableOutput("table4"))
)),
server = function(input, output, session) {
output$table1 = DT::renderDataTable({ df }, options = list(dom = 't'))
df2 <- reactive ({
(df %>% filter(empName %in% input$Search)%>% select(empID))
})
output$table2 = DT::renderDataTable({
req(input$Search)
df2()}, options = list(dom = 't'))
df3 <- reactive({
if (input$Search != "") {
sqldf(paste0("SELECT *
FROM df WHERE empName LIKE '%",input$Search,"%'"))
}})
output$table3 = DT::renderDataTable({
req(input$Search)
df3()}, options = list(dom = 't'))
df4 <- reactive ({
SelectedNames <-stringr::str_c(stringr::str_c("'", input$Search, "'"), collapse = ',')
sqldf(paste0("SELECT empAge, empSalary
FROM df WHERE empName IN (",SelectedNames,") "))
})
output$table4 = DT::renderDataTable({
req(input$Search)
df4()}, options = list(dom = 't'))
})
I am working with MySQL queries.
In Table 1 the data displayed is the whole employee dataframe , I cannot do that for thousands of rows.
In table 2 I select the employee names from selectize but display the corresponding IDs .
In Table 3, it only shows one selected value from the selectize.
In table 4, the code allows to query other details from multiple selection of the selectizeInput.
What I am looking for is to be able to select multiple names from selectizeInput but pass the corresponding multiple employee IDs to the Mysql query to get the results like in Table 4.
Thus basically combine the ability to select names but pass the values of the Id column to allow mutiple select in a query.
I have simplified your reactive expression, added the Geo as a initial selection, and moved selectizeInput to server side. Try this.
EDIT: I have updated the answer to remove initial selection.
###### updated answer on 8Sep2020
survey <- data.frame(name = c("Oberösterreich", "Северозападен", "Κύπρος", "Strední Cechy", "Severovýchod", "Praha"),
geo = c("AT31", "BG31", "CY00", "CZ02", "CZ05", "CZ01"),
population =c(100409314, 54086980, 30961705, 164741605, 156857074, 93166890))
ui = fluidPage(
fluidRow(
wellPanel(
uiOutput("regionorgeo")
)),
fluidRow(DTOutput('table')),
)
server = function(input, output, session){
output$regionorgeo <- renderUI({
selectizeInput(
'Geo',
label = "Geo Select",
choices = survey$geo,
selected=1,
options = list(
placeholder = 'Geo Region',
maxOptions = 1000,
maxItems = 10,
searchConjunction = 'and'
)
)
})
geonamesdata <- reactive({
req(input$Geo)
data <- filter(survey, geo %in% as.character(input$Geo))
data
})
output$table <- DT::renderDataTable(geonamesdata(),
selection = 'single',
options = list(searching = FALSE,pageLength = 10),
server = FALSE, escape = FALSE,rownames= FALSE)
}
shinyApp(ui, server)
Related
This is the next step in my attempt to build a user-friendly transition matrix in R, a follow-on to post How to add a vertical line to the first column header in a data table?. I have been spoiled by the ease of drafting eye-friendly tables in Excel and have been struggling with this in R Shiny.
Running the MWE code at the bottom generates the transition table shown on the left side of the image below (with my comments overlaying). Expressing my question in Excel-speak, I'm trying to merge the top 2 cells (rows) in the left-most column (call them cells A1 and A2), eliminate the small bit of line just above "to_state" (cell A2)(item #1 in the image), eliminate that first column's header "to_state" (in cell A2)(item #2 in the image), and into that merged column header space insert an object similar to the object hovering over the "From" columns to the right, that states "To state where end period = x", where x is the value of object transTo() (item #3 in the image). Any suggestions for doing this? Using DT for the table rendering if possible.
I'm open to any other suggestion for drafting a user-friendly, understandable state transition matrix that delineates to/from columns/rows and reactively shows the to/from periods.
Post Shiny: Merge cells in DT::datatable seems promising but it addresses merging rows in the body of the table and not header rows.
Please note that in the fuller code, the table dynamically contracts/expands based on the number of unique states detected in the underlying data. States can range from 2 to 12.
MWE code:
library(DT)
library(shiny)
library(dplyr)
library(htmltools)
library(data.table)
data <-
data.frame(
ID = c(1,1,1,2,2,2,3,3,3),
Period = c(1, 2, 3, 1, 2, 3, 1, 2, 3),
Values = c(5, 10, 15, 0, 2, 4, 3, 6, 9),
State = c("X0","X1","X2","X0","X2","X0", "X2","X1","X0")
)
numTransit <- function(x, from=1, to=3){
setDT(x)
unique_state <- unique(x$State)
all_states <- setDT(expand.grid(list(from_state = unique_state, to_state = unique_state)))
dcast(x[, .(from_state = State[from],
to_state = State[to]),
by = ID]
[,.N, c("from_state", "to_state")]
[all_states,on = c("from_state", "to_state")],
to_state ~ from_state, value.var = "N"
)
}
ui <- fluidPage(
tags$head(tags$style(".datatables .display {margin-left: 0;}")), # < left-align the table
h4(strong("Base data frame:")),
tableOutput("data"),
h4(strong("Transition table inputs:")),
numericInput("transFrom", "From period:", 1, min = 1, max = 3),
numericInput("transTo", "To period:", 2, min = 1, max = 3),
h4(strong("Output transition table:")),
DTOutput("resultsDT"),
)
server <- function(input, output, session) {
results <-
reactive({
results <- numTransit(data, input$transFrom, input$transTo) %>%
replace(is.na(.), 0) %>%
bind_rows(summarise_all(., ~(if(is.numeric(.)) sum(.) else "Sum")))
results <- cbind(results, Sum = rowSums(results[,-1]))
})
output$data <- renderTable(data)
output$resultsDT <- renderDT(server=FALSE, {
req(results())
datatable(
data = results(),
rownames = FALSE,
filter = 'none',
container = tags$table(
class = 'display',
tags$thead(
tags$tr(
tags$th(colspan = 1, '', style = "border-right: solid 1px;"),
tags$th(colspan = 10, sprintf('From state where initial period = %s', input$transFrom))
),
tags$tr(
mapply(tags$th, colnames(results()), style = sprintf("border-right: solid %spx;", c(1L, rep(0, ncol(results())-1L))), SIMPLIFY = FALSE)
)
)
),
options = list(scrollX = F
, dom = 'ft'
, lengthChange = T
, pagingType = "numbers" # hides Next and Previous buttons
, autoWidth = T
, info = FALSE # hide the "Showing 1 of 2..." at bottom of table
, searching = FALSE # removes search box
),
class = "display"
) %>%
formatStyle(c(1), `border-right` = "solid 1px")
})
}
shinyApp(ui, server)
Please reference these related posts that lead to the solution shown at the bottom. The posts that built up to this solution are How to merge to row cells in data table?, How to add a vertical line to the first column header in a data table?, and How to add reactive object to secondary column header in output table?
Solution:
library(DT)
library(shiny)
library(dplyr)
library(htmltools)
library(data.table)
data <-
data.frame(
ID = c(1,1,1,2,2,2,3,3,3),
Period = c(1, 2, 3, 1, 2, 3, 1, 2, 3),
Values = c(5, 10, 15, 0, 2, 4, 3, 6, 9),
State = c("X0","X1","X2","X0","X2","X0", "X2","X1","X0")
)
numTransit <- function(x, from=1, to=3){
setDT(x)
unique_state <- unique(x$State)
all_states <- setDT(expand.grid(list(from_state = unique_state, to_state = unique_state)))
dcast(x[, .(from_state = State[from],
to_state = State[to]),
by = ID]
[,.N, c("from_state", "to_state")]
[all_states,on = c("from_state", "to_state")],
to_state ~ from_state, value.var = "N"
)
}
ui <- fluidPage(
tags$head(tags$style(".datatables .display {margin-left: 0;}")), # < left-align the table
h4(strong("Base data frame:")),
tableOutput("data"),
h4(strong("Transition table inputs:")),
numericInput("transFrom", "From period:", 1, min = 1, max = 3),
numericInput("transTo", "To period:", 2, min = 1, max = 3),
h4(strong("Output transition table:")),
DTOutput("resultsDT"),
)
server <- function(input, output, session) {
results <-
reactive({
results <- numTransit(data, input$transFrom, input$transTo) %>%
replace(is.na(.), 0) %>%
bind_rows(summarise_all(., ~(if(is.numeric(.)) sum(.) else "Sum")))
results <- cbind(results, Sum = rowSums(results[,-1]))
})
output$data <- renderTable(data)
output$resultsDT <- renderDT(server=FALSE, {
req(results())
datatable(
data = results(),
rownames = FALSE,
filter = 'none',
container = tags$table(
class = 'display',
tags$thead(
tags$tr(
tags$th(rowspan = 2, sprintf('To state where end period = %s', input$transTo), style = "border-right: solid 1px;"),
tags$th(colspan = 10, sprintf('From state where initial period = %s', input$transFrom))
),
tags$tr(
mapply(tags$th, colnames(results())[-1], style = sprintf("border-right: solid %spx;", rep(0, ncol(results()) - 1L)), SIMPLIFY = FALSE)
)
)
),
options = list(scrollX = F
, dom = 'ft'
, lengthChange = T
, pagingType = "numbers" # hides Next and Previous buttons
, autoWidth = T
, info = FALSE # hide the "Showing 1 of 2..." at bottom of table
, searching = FALSE # removes search box
),
class = "display"
) %>%
formatStyle(c(1), `border-right` = "solid 1px")
})
}
shinyApp(ui, server)
I am working on a transition table module and am wrestling with how to make the output understandable for the user. I used to prepare transition tables in Excel; making the table legible was super easy but deriving the data for table output took hours. Now my problem is the opposite with R: takes a few seconds to generate the table output from millions of rows of data but table presentation is far from simple.
To start, I would like to reflect the user's "From" input (object transFrom) in this reactive table's secondary column header as shown in the image below; any suggestions for how to do this? I am completely clueless with respect to html. I had found this solution here R Shiny app - Render Data Table with double header, and I like it because it uses DT, which I use throughout (though I would have preferred the base R table, using Shiny renderTable(), but I could not make that work). I have researched this and found other packages for drafting nice tables but I am avoiding "package bloat" and would rather stick with base R, Shiny, data.table, and DT package IF POSSIBLE.
Note that the columns reflect the transition states FROM, and the rows reflect the transition states TO.
Here is the MWE code for actively rendering the above:
library(data.table)
library(dplyr)
library(shiny)
# custom table container
sketch = htmltools::withTags(table(
class = 'display',
thead(
tr(
th(colspan = 1, ''),
th(colspan = 10, 'From state where initial period is = ')
),
tr(
lapply(colnames(results), th)
)
)
))
data <-
data.frame(
ID = c(1,1,1,2,2,2,3,3,3),
Period = c(1, 2, 3, 1, 2, 3, 1, 2, 3),
Values = c(5, 10, 15, 0, 2, 4, 3, 6, 9),
State = c("X0","X1","X2","X0","X2","X0", "X2","X1","X0")
)
ui <- fluidPage(
tags$head(tags$style(".datatables .display {margin-left: 0;}")), # < left-align the table
h4(strong("Base data frame:")),
tableOutput("data"),
h4(strong("Transition table inputs:")),
numericInput("transFrom", "From period:", 1, min = 1, max = 3),
numericInput("transTo", "To period:", 2, min = 1, max = 3),
h4(strong("Output transition table:")),
DTOutput("results"),
)
server <- function(input, output) {
numTransit <- function(x, from=1, to=3){
setDT(x)
unique_state <- unique(x$State)
all_states <- setDT(expand.grid(list(from_state = unique_state, to_state = unique_state)))
dcast(x[, .(from_state = State[from],
to_state = State[to]),
by = ID]
[,.N, c("from_state", "to_state")]
[all_states,on = c("from_state", "to_state")],
to_state ~ from_state, value.var = "N"
)
}
results <-
reactive({
results <- numTransit(data,input$transFrom,input$transTo) %>%
replace(is.na(.), 0) %>%
bind_rows(summarise_all(., ~(if(is.numeric(.)) sum(.) else "Sum")))
results <- cbind(results, Sum = rowSums(results[,-1]))
})
output$data <- renderTable(data)
output$results <- renderDT(server=FALSE,{
results() %>%
datatable(rownames = FALSE,
filter = 'none',
container = sketch,
options = list(scrollX = F
, dom = 'ft'
, lengthChange = T
, pagingType = "numbers" # hides Next and Previous buttons
, autoWidth = T
, info = FALSE # hide the "Showing 1 of 2..." at bottom of table
,searching = FALSE # removes search box
),
class = "display"
)
})
}
shinyApp(ui, server)
It seems that htmltools::withTags doesn't play well with using shiny inputs (I filed an issue here).
Please check the following:
library(DT)
library(shiny)
library(htmltools)
library(data.table)
data <-
data.frame(
ID = c(1,1,1,2,2,2,3,3,3),
Period = c(1, 2, 3, 1, 2, 3, 1, 2, 3),
Values = c(5, 10, 15, 0, 2, 4, 3, 6, 9),
State = c("X0","X1","X2","X0","X2","X0", "X2","X1","X0")
)
numTransit <- function(x, from=1, to=3){
setDT(x)
unique_state <- unique(x$State)
all_states <- setDT(expand.grid(list(from_state = unique_state, to_state = unique_state)))
dcast(x[, .(from_state = State[from],
to_state = State[to]),
by = ID]
[,.N, c("from_state", "to_state")]
[all_states,on = c("from_state", "to_state")],
to_state ~ from_state, value.var = "N"
)
}
ui <- fluidPage(
tags$head(tags$style(".datatables .display {margin-left: 0;}")), # < left-align the table
h4(strong("Base data frame:")),
tableOutput("data"),
h4(strong("Transition table inputs:")),
numericInput("transFrom", "From period:", 1, min = 1, max = 3),
numericInput("transTo", "To period:", 2, min = 1, max = 3),
h4(strong("Output transition table:")),
DTOutput("resultsDT"),
)
server <- function(input, output, session) {
results <-
reactive({
results <- numTransit(data, input$transFrom, input$transTo) %>%
replace(is.na(.), 0) %>%
bind_rows(summarise_all(., ~(if(is.numeric(.)) sum(.) else "Sum")))
results <- cbind(results, Sum = rowSums(results[,-1]))
})
output$data <- renderTable(data)
output$resultsDT <- renderDT(server=FALSE, {
req(results())
datatable(
data = results(),
rownames = FALSE,
filter = 'none',
container = tags$table(
class = 'display',
tags$thead(
tags$tr(
tags$th(colspan = 1, ''),
tags$th(colspan = 10, sprintf('From state where initial period is = %s', input$transFrom))
),
tags$tr(
lapply(colnames(results()), tags$th)
)
)
),
options = list(scrollX = F
, dom = 'ft'
, lengthChange = T
, pagingType = "numbers" # hides Next and Previous buttons
, autoWidth = T
, info = FALSE # hide the "Showing 1 of 2..." at bottom of table
, searching = FALSE # removes search box
),
class = "display"
)
})
}
shinyApp(ui, server)
I would like to add a vertical line to a DT table column header. There is guidance for adding this line in post How can I add a vertical line to a datatable?, but it applies to a static table where columns are manually set whereas in my MWE code (at bottom), the columns are set using the lapply() function in a reactive setting. So I'm having trouble using this guidance in my particular circumstances.
Any suggestions for adding a vertical line to the right of the left-most column header labeled "to_state"? As shown in this image which shows a portion of the output window when running the MWE code:
Please note that in the fuller code this MWE derives from, the table expands/contracts dynamically depending on the number of unique states detected in the underlying data. Therefore I can't use a static table set up like in the referenced related post above.
Once this is resolved, I'll have several additional questions as I struggle to make a transition table readily understandable for users (such as change the "to_state" left-most column header to "To end Period = [xxx]", but that will be addressed in another post). I'm tackling this formatting issue incrementally in baby steps.
I am very unfamiliar with HTML, CSS.
Here is the MWE code:
library(DT)
library(shiny)
library(htmltools)
library(data.table)
data <-
data.frame(
ID = c(1,1,1,2,2,2,3,3,3),
Period = c(1, 2, 3, 1, 2, 3, 1, 2, 3),
Values = c(5, 10, 15, 0, 2, 4, 3, 6, 9),
State = c("X0","X1","X2","X0","X2","X0", "X2","X1","X0")
)
numTransit <- function(x, from=1, to=3){
setDT(x)
unique_state <- unique(x$State)
all_states <- setDT(expand.grid(list(from_state = unique_state, to_state = unique_state)))
dcast(x[, .(from_state = State[from],
to_state = State[to]),
by = ID]
[,.N, c("from_state", "to_state")]
[all_states,on = c("from_state", "to_state")],
to_state ~ from_state, value.var = "N"
)
}
ui <- fluidPage(
tags$head(tags$style(".datatables .display {margin-left: 0;}")), # < left-align the table
h4(strong("Base data frame:")),
tableOutput("data"),
h4(strong("Transition table inputs:")),
numericInput("transFrom", "From Period:", 1, min = 1, max = 3),
numericInput("transTo", "To Period:", 2, min = 1, max = 3),
h4(strong("Output transition table:")),
DTOutput("resultsDT"),
)
server <- function(input, output, session) {
results <-
reactive({
results <- numTransit(data, input$transFrom, input$transTo) %>%
replace(is.na(.), 0) %>%
bind_rows(summarise_all(., ~(if(is.numeric(.)) sum(.) else "Sum")))
results <- cbind(results, Sum = rowSums(results[,-1]))
})
output$data <- renderTable(data)
output$resultsDT <- renderDT(server=FALSE, {
req(results())
datatable(
data = results(),
rownames = FALSE,
filter = 'none',
container = tags$table(
class = 'display',
tags$thead(
tags$tr(
tags$th(colspan = 1, '', style = "border-right: solid 1px;"),
tags$th(colspan = 10, sprintf('From initial Period = %s', input$transFrom))
),
tags$tr(
lapply(colnames(results()),
tags$th
)
),
)
),
options = list(scrollX = F
, dom = 'ft'
, lengthChange = T
, pagingType = "numbers" # hides Next and Previous buttons
, autoWidth = T
, info = FALSE # hide the "Showing 1 of 2..." at bottom of table
, searching = FALSE # removes search box
),
class = "display"
) %>%
formatStyle(c(1), `border-right` = "solid 1px")
})
}
shinyApp(ui, server)
We can use mapply instead of lapply to control the style parameter:
library(DT)
library(shiny)
library(dplyr)
library(htmltools)
library(data.table)
data <-
data.frame(
ID = c(1,1,1,2,2,2,3,3,3),
Period = c(1, 2, 3, 1, 2, 3, 1, 2, 3),
Values = c(5, 10, 15, 0, 2, 4, 3, 6, 9),
State = c("X0","X1","X2","X0","X2","X0", "X2","X1","X0")
)
numTransit <- function(x, from=1, to=3){
setDT(x)
unique_state <- unique(x$State)
all_states <- setDT(expand.grid(list(from_state = unique_state, to_state = unique_state)))
dcast(x[, .(from_state = State[from],
to_state = State[to]),
by = ID]
[,.N, c("from_state", "to_state")]
[all_states,on = c("from_state", "to_state")],
to_state ~ from_state, value.var = "N"
)
}
ui <- fluidPage(
tags$head(tags$style(".datatables .display {margin-left: 0;}")), # < left-align the table
h4(strong("Base data frame:")),
tableOutput("data"),
h4(strong("Transition table inputs:")),
numericInput("transFrom", "From Period:", 1, min = 1, max = 3),
numericInput("transTo", "To Period:", 2, min = 1, max = 3),
h4(strong("Output transition table:")),
DTOutput("resultsDT"),
)
server <- function(input, output, session) {
results <-
reactive({
results <- numTransit(data, input$transFrom, input$transTo) %>%
replace(is.na(.), 0) %>%
bind_rows(summarise_all(., ~(if(is.numeric(.)) sum(.) else "Sum")))
results <- cbind(results, Sum = rowSums(results[,-1]))
})
output$data <- renderTable(data)
output$resultsDT <- renderDT(server=FALSE, {
req(results())
datatable(
data = results(),
rownames = FALSE,
filter = 'none',
container = tags$table(
class = 'display',
tags$thead(
tags$tr(
tags$th(colspan = 1, '', style = "border-right: solid 1px;"),
tags$th(colspan = 10, sprintf('From initial Period = %s', input$transFrom))
),
tags$tr(
mapply(tags$th, colnames(results()), style = sprintf("border-right: solid %spx;", c(1L, rep(0, ncol(results())-1L))), SIMPLIFY = FALSE)
)
)
),
options = list(scrollX = F
, dom = 'ft'
, lengthChange = T
, pagingType = "numbers" # hides Next and Previous buttons
, autoWidth = T
, info = FALSE # hide the "Showing 1 of 2..." at bottom of table
, searching = FALSE # removes search box
),
class = "display"
) %>%
formatStyle(c(1), `border-right` = "solid 1px")
})
}
shinyApp(ui, server)
I'm developping a Shiny app to filter a database (like Excel), and I'd like to stop all the calculation of the app when a Drop Down Button is open. Do you know how could I do that please ? It's my first Shiny app, so I'm pretty sure that I made some silly mistakes.
In my Drop Down Button, I have a CheckBoxGroupInput, with the different choices for one variable of my database. Problem : I have to wait a few seconds between each selection inside the CheckBoxGroupInput, because the app is refreshing for each additionnal choice in the CheckBox.
An example for one variable :
ui :
dropdownButton(
label = "Country :", status = "default", width = 200, circle = FALSE,
actionButton(inputId = "country_all", label = "(Un)select all"),
uiOutput("countrybis")
),
verbatimTextOutput(outputId = "country_print")
server :
Function for refreshing each list in the different CheckBox :
Function_List_Data <- function(p_type, p_processchoice, p_year, p_variable, p_product, p_country,
p_item, p_season, p_region, p_calcamp){
if(p_processchoice == "GROSSVAR"){
data <- dataset_var[YEARBIS >= p_year[1] & YEARBIS <= p_year[2],]}
else if(p_processchoice == "YIELD"){
data <- dataset_rdt[YEARBIS >= p_year[1] & YEARBIS <= p_year[2],]}
else{data <- dataset[YEARBIS >= p_year[1] & YEARBIS <= p_year[2],]}
if (p_region == 2) {data <- data[REGION %in% list("EU-15","EU-27","EU-28")]}
else if (p_region == 3) {data <- data[REGION %in% list("C.I.S.")]}
if (p_calcamp == 2) {data <- data[`CAMPAIGN/CALENDAR` == "CAMPAIGN",]}
else if (p_calcamp == 3) {data <- data[`CAMPAIGN/CALENDAR` == "CALENDAR",]}
else if (p_calcamp == 4) {data <- data[`CAMPAIGN/CALENDAR` == "OTHERS",]}
if (!is.null(p_variable)) {data <- data[VARIABLE %in% p_variable]}
if (!is.null(p_product)) {data <- data[PRODUCT %in% p_product,]}
if (!is.null(p_country)) {data <- data[COUNTRY %in% p_country,]}
if (!is.null(p_item)) {data <- data[ITEM %in% p_item,]}
if (!is.null(p_season)) {data <- data[SEASON %in% p_season,]}
if(nrow(data)<1){ data <- data[1,] }
if (p_type == "VARIABLE"){List <- unique(unlist(data$VARIABLE), use.names = FALSE)}
else if (p_type == "PRODUCT"){List <- unique(unlist(data$PRODUCT), use.names = FALSE)}
else if (p_type == "COUNTRY"){List <- unique(unlist(data$COUNTRY), use.names = FALSE)}
else if (p_type == "ITEM"){List <- unique(unlist(data$ITEM), use.names = FALSE)}
else if (p_type == "SEASON"){List <- unique(unlist(data$SEASON), use.names = FALSE)}
return(List)
}
Calculation for the Country column :
Country_List <- reactive({
Function_List_Data(p_type = "COUNTRY",
p_processchoice = input$dataprocess_choice,
p_year = input$year,
p_variable = input$variable_list,
p_product = input$product_list,
p_country = NULL,
p_item = input$item_list,
p_season = input$season_list,
p_region = input$region,
p_calcamp = input$campaign_calendar)})
observeEvent(input$country_all, {
if (is.null(input$country_list)) {
updateCheckboxGroupInput(session = session, inputId = "country_list", selected = Country_List())}
else {updateCheckboxGroupInput(session = session, inputId = "country_list", selected = "")}
})
output$country_print <- renderPrint({
if(is.null(input$country_list)){"- ALL -"}
else{as.matrix(input$country_list)}
})
output$countrybis <- renderUI({
checkboxGroupInput(inputId = "country_list", label = "Choose", choices = sort(Country_List()), selected = input$country_list)
})
EDIT :
When I calculate the Country_List only when I click on the DropdownButton, it's not working, you can see the error on the screen :
Error received : the Country_List is calculate after the CheckBox is print
.
Button Select All / Unselect All :
observeEvent(input$country_all, {
Country_List <- Function_List_Data(p_type = "COUNTRY",
p_processchoice = input$dataprocess_choice,
p_year = input$year,
p_variable = input$variable_list,
p_product = input$product_list,
p_country = NULL,
p_item = input$item_list,
p_season = input$season_list,
p_region = input$region,
p_calcamp = input$campaign_calendar)
if (is.null(input$country_list)) {
updateCheckboxGroupInput(session = session, inputId = "country_list", selected = Country_List)}
else {updateCheckboxGroupInput(session = session, inputId = "country_list", selected = "")}})
RenderPrint :
output$country_print <- renderPrint({
if(is.null(input$country_list)){"- ALL -"}
else{as.matrix(input$country_list)}})
CheckBox :
output$countrybis <- renderUI({
observeEvent(input$Country_DropDown,{
print("bla")
Country_List <- Function_List_Data(p_type = "COUNTRY",
p_processchoice = input$dataprocess_choice,
p_year = input$year,
p_variable = input$variable_list,
p_product = input$product_list,
p_country = NULL,
p_item = input$item_list,
p_season = input$season_list,
p_region = input$region,
p_calcamp = input$campaign_calendar)
})
checkboxGroupInput(inputId = "country_list", label = "Choose", choices = sort(Country_List), selected = input$country_list) })
I am new to the leaflet package.
I am trying to draw two types of polygons and let the user select them and see the borders. These polygons have labels and I want to display them by default. At the moment the labels are displayed only on mouse hover.
Basically what I want is to let the user search for the polygon label on the map.
Given below is my code.
shp <- readOGR(dsn = 'shapes'
,layer = 'SAB')
postcode <- readOGR(dsn = 'shapes'
,layer = 'Postcode')
CRS_WGS84 <- '+proj=longlat +datum=WGS84 +no_defs +ellps=WGS84 +towgs84=0,0,0'
t_shp <- spTransform(shp, CRS(CRS_WGS84))
sab_shp <- raster::aggregate(t_shp, by='SMALL_AREA')
dat <- data.table(shp#data)
sabLabels <- sprintf('<strong>SAB: %s', t_shp$SMALL_AREA) %>% lapply(HTML)
postcode <- readOGR(dsn = 'shapes'
,layer = 'Postcode')
CRS_WGS84 <- '+proj=longlat +datum=WGS84 +no_defs +ellps=WGS84 +towgs84=0,0,0'
t_shp2 <- spTransform(postcode, CRS(CRS_WGS84))
postcode_shp <- raster::aggregate(t_shp2, by='RoutingKey')
dat2 <- data.table(postcode#data)
postcodeLabels <- sprintf('<strong>SAB: %s', t_shp2$RoutingKey) %>% lapply(HTML)
leaflet() %>%
addTiles() %>% #using default does not allow html export to include the underlying
#OSM layer
addProviderTiles('OpenStreetMap.Mapnik') %>%
addPolygons( data = t_shp
,stroke = T
,fillColor = 'grey'
,fillOpacity = 0.2
,color = 'blue'
,weight = 0.5
,label = sabLabels
,group = 'SABS'
,highlightOptions = highlightOptions(color = "blue", weight = 7,
bringToFront = TRUE)
#,labelOptions = labelOptions(noHide = TRUE, textOnly = TRUE, opacity = 0.5 , textsize='15px')
) %>%
addPolygons( data = t_shp2
,stroke = T
,fillOpacity = 0
,color = 'black'
,weight = 1.5
,label = postcodeLabels
,group = 'PostCodes'
) %>%
addLayersControl(
overlayGroups = c(
'SABS'
,'PostCodes'
)
,options = layersControlOptions((collapsed = F))
)