Initialize filters of SelectizeGroupUI with the first value - shiny

Does anyone know if it is possible to initialize the filters defined in the selectizeGroupUI with the first value in each of the filters? Something like the "selected" option in the selectInput. Let's say I have the following code:
if (interactive()) {
library(shiny)
library(shinyWidgets)
data("mpg", package = "ggplot2")
ui <- fluidPage(
fluidRow(
column(
width = 10, offset = 1,
tags$h3("Filter data with selectize group"),
panel(
pickerInput(
inputId = "car_select",
choices = unique(mpg$manufacturer),
options = list(
`live-search` = TRUE,
title = "None selected"
)
),
selectizeGroupUI(
id = "my-filters",
params = list(
manufacturer = list(inputId = "manufacturer", title = "Manufacturer:"),
model = list(inputId = "model", title = "Model:"),
trans = list(inputId = "trans", title = "Trans:"),
class = list(inputId = "class", title = "Class:")
)
),
status = "primary"
),
DT::dataTableOutput(outputId = "table")
)
)
)
server <- function(input, output, session) {
mpg_filter <- reactive({
subset(mpg, manufacturer %in% input$car_select)
})
res_mod <- callModule(
module = selectizeGroupServer,
id = "my-filters",
data = mpg_filter,
vars = c("manufacturer", "model", "trans", "class")
)
output$table <- DT::renderDataTable({
req(res_mod())
res_mod()
})
}
shinyApp(ui, server)
}
If I select "audi" in the pickerInput, is it possible that instantly the filters of "Manufacturer", "Model", "Trans" and "Class" take the value of the first option they have?
I tried to assign a value to the filter with input[["my-filters-model"]] but it shows an error that Can't modify read-only reactive value

Related

Reactive Dataset on Download Handler

I have a shiny app linked to a duckdb. Since I have a very big dataset I just want to load in 10'000 rows. However as soon as the user downloads the dataset it should download the entire dataset and not just the first 10'000 rows. So I guess there should be some kind of if condition where i specify the "LIMIT 10000" which reacts on the download handler. However, I dont know how to change the LIMIT based on the download handler.
BestandeslisteDaten_UI <- function(id3, mydb, data_Vertrag){
ns <- NS(id3)
tagList(
fluidRow(
box(
title = "Daten Bestandesliste", status = "primary", solidHeader = TRUE,
collapsible = TRUE, width=9,
DTOutput(ns("dt31"))
),
box(
title = "Einschränkung des Datenset", status = "primary", solidHeader = TRUE,
collapsible = TRUE, width=3, height = "110em",
downloadButton(ns("download32"),"Download entire Table as csv")
)
)
)
}
BestandeslisteDaten_Server <- function(id3, mydb, data_Vertrag){
moduleServer(
id3,
function(input, output, session){
filter_BestandVertrag_Daten <- reactive({
query <- glue_sql("SELECT * FROM data_Vertrag",
.con = mydb)
add_where <- TRUE
query <- glue_sql(query, " LIMIT 10000", .con = mydb)
print(query)
dt <- as.data.table(dbGetQuery(mydb, query))
print(dt)
dt
})
# Data Table
output$dt31 <- renderDT({
filter_BestandVertrag_Daten() %>%
datatable(
extensions = 'Buttons',
options = list(
server = TRUE,
lengthMenu=c(10, 100),
scrollX = TRUE,
scrollY = "500px",
dom = 'Blfrtip'
))
})
# Download Datatable
output$download32 <- downloadHandler(
filename = function() {
paste("Bestandesliste_", Sys.Date(), ".csv", sep="")
},
content = function(file) {
write.csv(filter_BestandVertrag_Daten(), file)
}
)
}
)
}

Is there a way to automatically upload the excel file in R

Is there a way to automatically upload the excel file.
Right now, the user has to manually upload the excel file(file.xlsx) that is kept under project folder.
Now the expected output is the moment the user clicks on "Automatically Upload the exceil file", the file should get uploaded.
Is there a way to achieve this? Let me know if this makes sense
library(tidyverse)
library(shiny)
library(shinydashboard)
library(DT)
ui <-
dashboardPage(
skin = "green",
dashboardHeader(
title = "Test",
titleWidth = 280
),
dashboardSidebar(
width = 280,
sidebarMenu(
menuItem(text = "File(s) Upload", tabName = "Files", icon = icon("file-upload")),
menuItem(text = "Output", tabName = "Out1", icon = icon("file-upload"))
)
),
dashboardBody(
tabItems(
tabItem(
tabName = "Files",
fluidRow(
column(
width = 4,
inputPanel(
fileInput(inputId = "File1", label = "File", multiple = TRUE, accept = c(".xlsx")),
selectInput(inputId = "Sheet1", label = "Select sheet", choices = NULL, selected = NULL),
actionButton("sub", "Automatically Upload the exceil file")
)
)
)
),
tabItem(
tabName = "Out1",
fluidRow(column(width = 10, strong("Data")), align = "center"),
br(),
fluidRow(dataTableOutput("Data1"))
)
)
)
)
server <- function(input, output){
# Populate the drop down menu with the names of the different Excel Sheets, but
# only after a new file is supplied
observe({
sheet_names <- readxl::excel_sheets(input$File1$datapath)
shiny::updateSelectInput(
inputId = "Sheet1",
choices = sheet_names,
selected = sheet_names[[1]]
)
}) %>%
bindEvent(input$File1)
# When the drop down meny is populated, read the selected sheet from the Excel
# file
thedata <- reactive({
req(input$Sheet1)
readxl::read_xlsx(input$File1$datapath, sheet = input$Sheet1)
})
output$Data1 <-
renderDataTable(
thedata()
, extensions = "Buttons"
, options = list(
dom = "Bfrtip"
, buttons = c("copy", "csv", "excel", "pdf", "print")
)
)
# observe({
# print(reactiveValuesToList(input, all.names = FALSE))
# })
}
runApp(
list(ui = ui, server = server)
, launch.browser = TRUE
)

shinyStore issue saving f7SmartSelect with multiple selection with Error in unclass(x) : cannot unclass an environment

I am trying to build a shiny app with shinyMobile, and storing the results using shinyStore, I have been looking at several answers but I haven't been able to fix this. I think there might be an issue with the multiple option.
Here is the code:
library(shiny)
library(shinyMobile)
library(shinyStore)
Species_List <- structure(list(Scientific_name = c("Juncus alpinoarticulatus ssp. nodulosus",
"Diphasiastrum complanatum ssp. complana-tum", "Rubus macrophyllus",
"Equisetum scirpoides", "Trifolium hybridum ssp. hybridum", "Narthecium ossifragum",
"Peucedanum oreoselinum", "Sonchus oleraceus", "Juncus subnodulosus",
"Minuartia viscosa"), Danish_name = c("siv, stilk-", "ulvefod, flad",
"brombær, storbladet", "padderok, tråd-", "kløver, alsike-",
"benbræk", "svovlrod, bakke-", "svinemælk, almindelig", "siv, butblomstret",
"norel, klæbrig")), row.names = c(NA, -10L), class = "data.frame")
shinyApp(
ui = f7Page(
title = "Species app",
f7SingleLayout(
navbar = f7Navbar(
title = "Select Species",
hairline = TRUE,
shadow = TRUE
),
toolbar = f7Toolbar(
position = "bottom",
f7Link(label = "Link 1", href = "https://www.google.com"),
f7Link(label = "Link 2", href = "https://www.google.com")
),
initStore("store", "shinyStore-ex1"),
# A button to save current input to local storage
actionButton("save", "Save", icon("save")),
# A button to clear the input values and local storage
actionButton("clear", "Clear", icon("stop")),
# main content
f7Shadow(
intensity = 16,
hover = TRUE,
f7SmartSelect(inputId = "SpeciesListSc",
label = "Select all species",
multiple = TRUE,
choices = unique(Species_List$Scientific_name),
virtualList = T,
openIn = "sheet")
)
)
),
server = function(input, output, session) {
observe({
if (input$save <= 0){
updateF7SmartSelect(session, inputId = "SpeciesListSc", selected = isolate(input$store)$SpeciesListSc, choices = unique(Species_List$Scientific_name), multiple = TRUE)
}
})
observe({
if (input$save > 0){
updateStore(session, name = "SpeciesListSc", isolate(input$SpeciesListSc))
}
})
}
)

Reactive graph dependent on multiple inputs

I have a reactive graph that takes in multiple inputs but it is dependent on all those inputs. Is there a way that the graph can take all the inputs but it isn't dependent on them all. For example if the user selects one drop down the graph will update and not need any of the other inputs but if the user adds a second input the graph will update with the 2nd input but not need the 3rd unless it is selected. Also if what the user has selected is null it won't change the graph.
UI:
ui <- dashboardPage(
dashboardHeader(title = "Human Trafficking"),
dashboardSidebar(
sidebarMenu(
selectInput("Source", "Choose a Data Source: ", choices = sort(unique(ngo$Data.Provided.By)), selected = NULL,
multiple = TRUE, selectize = TRUE, width = NULL, size = NULL),
dateInput("startdate", "Start Date:", value = "2009-01-01", format = "dd-mm-yyyy",
min = "2009-01-01", max = "2019-08-26"),
dateInput("enddate", "End Date:", value = "2019-08-27", format = "dd-mm-yyyy",
min = "2009-01-02", max = "2019-08-27"),
selectInput("Nationality", "Select a nation: ", choices = sort(unique(ngo$Victim.Nationality))),
actionButton("button", "Apply")
)
),
dashboardBody(
fluidRow(
box(width = 4, solidHeader = TRUE,
selectInput("traffickingType", "Choose a trafficking type: ", choices = sort(unique(ngo$Trafficking.Type)), selected = NULL,
multiple = TRUE, selectize = TRUE, width = NULL, size = NULL)
),
box(width = 4, solidHeader = TRUE,
selectInput("traffickingSubType", "Choose a trafficking sub type: ", choices = sort(unique(ngo$Trafficking.Sub.Type)), selected = NULL,
multiple = TRUE, selectize = TRUE, width = NULL, size = NULL)
),
box(width = 4, solidHeader = TRUE,
selectInput("gender", "Choose a gender: ", choices = sort(unique(ngo$Victim.Gender)), selected = NULL,
multiple = TRUE, selectize = TRUE, width = NULL, size = NULL)
)
),
fluidRow(
box(width = 6, solidHeader = TRUE, status = "primary",
title = "Trafficking Type",
plotlyOutput("coolplot", width = '750px', height = '600px')
),
box(width = 6, solidHeader = TRUE, status = "primary",
title = "Trafficking Sub-Type",
plotlyOutput("Sub", width = '750px', height = '600px')
)
)
)
)
Server:
server <- function(input, output, session) {
output$coolplot <- renderPlotly({
ngo <-
ngo %>%
filter(Victim.Nationality %in% input$Nationality,
Victim.Gender %in% input$gender,
Trafficking.Type %in% input$traffickingType,
Trafficking.Sub.Type %in% input$traffickingSubType,
Data.Provided.By %in% input$Source
) %>%
plot_ly(labels = ~Trafficking.Type, type = "pie")
})
}
I want to be able to allow the user to select one input and it will update graph and the more they add the graph will keep updating.
Not the neatest but what about separating the filtering as below:
server <- function(input, output, session) {
output$coolplot <- renderPlotly({
req(c(input$gender, input$traffickingType, input$traffickingSubType))
if(!is.null(input$Nationality)) {
ngo <- ngo %>% filter(Victim.Nationality %in% input$Nationality)
}
if(!is.null(input$gender)) {
ngo <- ngo %>% filter(Victim.Gender %in% input$gender)
}
if(!is.null(input$traffickingType)) {
ngo <- ngo %>% filter(Trafficking.Type %in% input$traffickingType)
}
if(!is.null(input$traffickingSubType)) {
ngo <- ngo %>% filter(Trafficking.Sub.Type %in% input$traffickingSubType)
}
if(!is.null(input$Source)) {
ngo <- ngo %>% filter(Data.Provided.By %in% input$Source)
}
plot_ly(ngo, labels = ~Trafficking.Type, type = "pie")
})
}
shinyApp(ui, server)
Update
based on comment below.
I added req(c(input$gender, input$traffickingType, input$traffickingSubType)).
I left out input$Nationality as that equals "A" on startup and input$Source I assumed but you can add input$source to the vector c(...) above if you want.

SelectInput and Leaflet not connecting

I am trying to use shinyApp with the leaflet package. I have tried using the "SelectInput" function in the dashboard to create a reactive map based on the input selected(country).However, I am not able to make the leaflet and the SelectInput connect with each other.
Here is my code:
library(shiny)
library(leaflet)
ui <- (fluidPage(
titlePanel(title = "Pig breeding countries in 2000 - Top 5"),
sidebarLayout(
sidebarPanel(
selectInput(inputId = "country",
label = "Select a country to view it's values (you can choose more than one):",
c("Brazil", "China", "Russia", "USA", "Vietnam"), multiple = TRUE
)
),
#mainPanel must be outside the sidebarLayout argument
mainPanel(leafletOutput("mymap", height = "500"),
leafletOutput("country")
))
)
)
server <- (function(input, output){
output$mymap <- renderLeaflet(input$country)
output$mymap <- renderLeaflet({
mymap = leaflet()
setView(mymap, lng = -16.882374406249937, lat = -1.7206857960062047, zoom = 0)
mymap = addProviderTiles(mymap, provider = "CartoDB.Positron")
mymap = addMarkers(mymap,lng = 101.901875, lat = 35.486703, popup = "China 35,500")
mymap = addMarkers(mymap,lng = -95.712891, lat = 37.090240, popup = "USA 6,267")
mymap = addMarkers(mymap,lng = 108.339537, lat = 14.315424, popup = "Vietnam 2,947")
mymap = addMarkers(mymap,lng = 37.618423, lat = 55.751244, popup = "Russia 3,070")
mymap = addMarkers(mymap,lng = -46.625290, lat = -23.533773, popup = "Brazil 3,020")}
})
shinyApp(ui, server)
Can someone advise how to link them?
There is no reactive environment between your drop-down selection and leaflet map in your code. Check in the below code to create reactive leaflet map.
library(shiny)
library(leaflet)
df <- read.csv("leaflet.csv")
ui <- (fluidPage(
titlePanel(title = "Pig breeding countries in 2000 - Top 5"),
sidebarLayout(
sidebarPanel( uiOutput("countrynames")
),
mainPanel(leafletOutput("mymap", height = "500")
))
)
)
server <- function(input, output){
output$countrynames <- renderUI({
selectInput(inputId = "country", label = "Select a country to view it's values (you can choose more than one):",
c(as.character(df$country)))
})
map_data <- reactive({
data <- data.frame(df[df$country == input$country,])
data$popup <- paste0(data$country, " ", data$number)
return(data)
})
output$mymap <- renderLeaflet({
leaflet(data = map_data()) %>%
# setView( lng = -16.882374406249937, lat = -1.7206857960062047, zoom = 0) %>%
addProviderTiles( provider = "CartoDB.Positron") %>%
addMarkers(lng = ~lng, lat = ~lat, popup = ~popup)
# addCircles(lng = ~lng, lat = ~lat, popup = ~popup)
})
}
shinyApp(ui, server)
Below is the csv file i have imported in code.
structure(list(lng = c(101.901875, -95.712891, 108.339537, 37.618423
), lat = c(35.486703, 37.09024, 14.315424, 55.751244), country = structure(c(1L,
3L, 4L, 2L), .Label = c("China", "Russia", "USA", "Vietnam"), class = "factor"),
number = c(35500L, 6267L, 2947L, 3070L)), .Names = c("lng",
"lat", "country", "number"), class = "data.frame", row.names = c(NA,
-4L))