selectInput Category selection - shiny

I have a selectInput code as like this
selectInput('x4', 'X4', choices = list(
Eastern = c(`New York` = 'NY', `New Jersey` = 'NJ'),
Western = c(`California` = 'CA', `Washington` = 'WA')
), selectize = FALSE)
Is it possible enable section on category, like Eastern, Western. If user selected Eastern both values have to load ( New Jersey and New York). Is it possible ?

library(shiny)
onInitialize <- "
function(){
var select = this.$input[0];
this.$dropdown_content.on('mousedown', function(e){
e.preventDefault();
return false;
}).on('click', '.optgroup-header', function(e){
var options = $(this).parent().find('.option');
var items = [];
options.each(function(i, opt){items.push($(opt).data('value'));});
var selections = select.selectize.items;
select.selectize.setValue(items.concat(selections));
});
}
"
shinyApp(
ui = fluidPage(
selectizeInput("state", "Choose a state:",
list(`East Coast` = list("NY", "NJ", "CT"),
`West Coast` = list("WA", "OR", "CA"),
`Midwest` = list("MN", "WI", "IA")),
multiple = TRUE,
options = list(
onInitialize = I(onInitialize)
)
)
),
server = function(input, output){}
)

Related

Initialize filters of SelectizeGroupUI with the first value

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

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))
}
})
}
)

button inside. DT::datatable does not render properly

I am trying to convert cells in a DT:datatable into clickable buttons, which action is append a new tab on my shiny app.
I have been using this post R Shiny: Handle Action Buttons in Data Table as reference but in my case the buttons shows up like this:
My app is a bit more complicated but I will try to re-create the part that does not work
This is an shorter version of my data.frame
mut_genes <- structure(list(acc_num = c("BM0042985", "BM0393251", "BM0673028"), disease = c("Sucrase isomaltase deficiency", "Metachromatic leukodystrophy", "Fatal surfactant deficiency"), gene = c("SI", "ARSA", "ABCA3"), chrom = c("3q25.2-q26.2", "22q13.31-qter", "16p13.3"), genename = c("Sucrase-isomaltase", "arylsulfatase A", "ATP binding cassette subfamily A member 3"), gdbid = c("120377", "119007", "3770735"), omimid = c("609845", "607574", "601615"), amino = c("Leu-Pro", "Glu-Lys", "Met-Ile"), deletion = c(NA_character_, NA_character_, NA_character_), insertion = c(NA_character_, NA_character_, NA_character_), codon = c(341L, 331L, 1L), codonAff = c(341L, 331L, 1L), hgvs = c("1022T>C", "991G>A", "3G>C"), hgvsAll = c("1022TtoC | L341P", "991GtoA | E331K", "3GtoC | M1I"), dbsnp = c("rs267607049", NA, NA), chromosome = c("3", "22", "16"), startCoord = c(165060026L, 50626052L, 2326464L), endCoord = c(165060026L, 50626052L, 2326464L), inheritance = c("AR", "AR", "AR"), gnomad_AC = c(NA_integer_, NA_integer_, NA_integer_), gnomad_AF = c(NA_real_, NA_real_, NA_real_), gnomad_AN = c(NA_integer_, NA_integer_, NA_integer_), mutype = c("missense", "missense", "initiation"), pmid = c("10903344", "12809637", "16641205"), pmidAll = c(NA, NA, "24871971"), base = c("M", "M", "M"), clinvarID = c("1413", NA, NA), clinvar_clnsig = c("Pathogenic", NA, NA), gene_id = c("2073", "190", "10")), row.names = c(NA, -3L), class = c("tbl_df", "tbl", "data.frame"))
library(shiny)
library(shinyjs)
library(tidyverse)
library(DT)
sidebar <- dashboardSidebar(
selectInput("search", label = "Search Options:",
choices = c("General", "Gene", "Mutation", "Reference", "Phenotype"), selected = "Gene"),
sidebarMenu(id="siderbarmenu", sidebarMenuOutput("menu"))
)
header <- dashboardHeader()
body <- dashboardBody(
tags$style(type="text/css",
".shiny-output-error { visibility: hidden; }",
".shiny-output-error:before { visibility: hidden; }",
".shiny-output-error:after { visibility: hidden; }"),
#ui
shinyjs::useShinyjs(),
tabItems(
tabItem("search_general", h1("A was done")),
tabItem(
tabName = "search_exact_gene",
tabsetPanel(
id = "tabs",
tabPanel(
title = "Main Dashboard",
value = "gene1",
fluidRow(
column(12,dataTableOutput("tablafilt_paste_genes"))
)
)
)
)
)
)
ui <- dashboardPage(header, sidebar, body)
And Here is the server part
server <- function(input, output, session) {
output$menu <- renderMenu({
my_general = list(
menuItem("Búsqueda general", tabName="search_general"),
conditionalPanel("input.siderbarmenu == 'search_general'",
textInput(inputId = "search_terms", label = "Search terms"),
selectInput("search_fields", label="Search choices", choices=c("All Fields", "Gene symbol",
"Gene description", "Chromosomal location", "HGNC/OMIM/GDB/Entrez ID", "RefSeq transcript",
"Disease/phenotype", "Gene Ontology"), selected = "Gene symbol"),
actionButton("submit", "Submit query")
)
)
my_gene = list(
menuItem("Búsqueda por gene", tabName="search_exact_gene"),
textInput(inputId = "search_exact_symbol", label = "Exact gene symbol only"),
actionButton("submit3", "Submit query")
)
if(input$search=="General"){
menu = my_general
} else if (input$search=="Gene"){
menu = my_gene
}
sidebarMenu(menu)
})
filtrado <- reactive({
dataset <- input$submit3
glist <- isolate(input$search_exact_symbol)
datos <- filter(mut_genes, gene %in% glist)
shinyInput <- function(FUN, len, id, ...) {
inputs <- character(len)
for (i in seq_len(len)) {
inputs[i] <- as.character(FUN(paste0(id, i), ...))
}
inputs
}
datos <- mutate(datos, Mutacion=shinyInput(
FUN = actionButton,
len = nrow(datos),
id = 'button_',
label = "Mutacion",
onclick = 'Shiny.onInputChange(\"select_button\", this.id)')
)
return(datos)
})
output$tablafilt_paste_genes <- DT::renderDataTable({
if(is.null(filtrado()))
return()
datos <- filtrado()
DT::datatable(datos, escape = FALSE,
rownames = FALSE,
style = 'bootstrap',
class = 'compact cell-border stripe hover',
filter = list(position = 'top', clear = FALSE),
extensions = c('Buttons', "FixedHeader", "Scroller"),
options = list(
stateSave = FALSE,
ordering = FALSE,
autoWidth = TRUE,
search = list(regex = TRUE, caseInsensitive = TRUE),
columnDefs = list(
list(
className = 'dt-center',
targets = 1:ncol(datos)-1L,
render = JS("function(data, type, row, meta) {",
"return type === 'display' && typeof data === 'string' && data.length > 10 ?",
"'<span title=\"' + data + '\">' + data.substr(0, 10) + '...</span>' : data;",
"}")
)
),
initComplete = JS(
"function(settings, json) {",
"$(this.api().table().header()).css({'font-size': '12px'});",
"}"),
sDom = '<"top">Brtp<"bottom">i', # remove search general box and keep the top filters
scrollX = TRUE,
deferRender=TRUE,
buttons = list('colvis'),
FixedHeader = TRUE,
pageLength = 25,
lengthMenu = list(c(25, 50, 100, -1), list('25', '50', '100', 'All'))
),
callback = JS('table.page(3).draw(false); "setTimeout(function() { table.draw(true); }, 300);"')) %>%
formatStyle(columns = colnames(.$x$data), `font-size` = "15px")
})
}
runApp(shinyApp(ui, server))
My ideal situation is recreate the acc_num column and make it a buttom clickable, but when I have tried with
shinyInput <- function(FUN, len, id, label,...) {
inputs <- character(len)
for (i in seq_len(len)) {
label <- datos$acc_num[i]
inputs[i] <- as.character(FUN(paste0(id, i), label=label, ...))
}
inputs
}
It happens the same, I still see the <button id => even when I set the datatable option escape to false
That's because of the quotes. Your render function generates <span title="<button id = "xxx" ...... and this causes the issue.
You don't want to apply the span to the buttons, so add the regex test !(/button/).test(data) in the conditions:
render = JS("function(data, type, row, meta) {",
"return type === 'display' && typeof data === 'string' && data.length > 10 && !(/button/).test(data) ? ",
"'<span title=\"' + data + '\">' + data.substr(0, 10) + '...</span>' : data;",
"}")

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))

EMailing Issue in Rshiny ::Attaching a Data Frame as pdf/.html from Shinyapps.io

[![i=iris
library(shiny)
library(mailR)
ui =fluidPage(
fluidRow(
div(id = "login",
wellPanel(title = "Mail your report",
textInput("to", label = "To:", placeholder = "To:"),
textInput("sub","Subject:"),
textInput("msg","Message:"),
actionButton("mailButton",label = "Send mail")
)
),tableOutput(outputId = "fo")
)
)
server = function(input, output, session) {
observeEvent(input$mailButton,{
isolate({
send.mail(from = "*****#gmail.com",
to = unlist(strsplit(input$to, ";", fixed = TRUE)),
subject = input$sub,
body = input$msg,
smtp = list(host.name = "smtp.gmail.com", port = 465, user.name = "****#gmail.com", passwd = "******", ssl = TRUE),
authenticate = TRUE,
attach.files = "fo",html = TRUE,
send = TRUE)
})
})
output$fo <- renderTable({
a<- as.data.frame(iris)
a$new <- a$Sepal.Length+a$Sepal.Width
a
})
}
runApp(list(ui=ui,server=server)) ][1]][1]
Here as we can see that in server function i have computed a new column a$new and entire data frame is saved back to a object so i need to mail this data frame as pdf/csv/.html any possible Format plz do guide on this
i=iris
library(shiny)
library(mailR)
a<- as.data.frame(iris)
write.csv(a,file="test.csv")
ui =fluidPage(
fluidRow(
div(id = "login",
wellPanel(title = "Mail your report",
textInput("to", label = "To:", placeholder = "To:"),
textInput("sub","Subject:"),
textInput("msg","Message:"),
actionButton("mailButton",label = "Send mail")
)
),tableOutput(outputId = "fo")
)
)
server = function(input, output, session) {
observeEvent(input$mailButton,{
isolate({
send.mail(from = "****#gmail.com",
to = unlist(strsplit(input$to, ";", fixed = TRUE)),
subject = input$sub,
body = input$msg,
smtp = list(host.name = "smtp.gmail.com", port = 465, user.name = "****#gmail.com", passwd = "nbwishes", ssl = TRUE),
authenticate = TRUE,
attach.files = "test1.csv",html = TRUE,
send = TRUE)
})
})
output$fo <- renderTable({
a<- as.data.frame(iris)
a$new <- a$Sepal.Length+a$Sepal.Width
write.csv(a,file="test1.csv")
})
}
runApp(list(ui=ui,server=server))