I am doing some timeseries analysis and have created a shiny app where when the app starts sample timeseries data is uploaded or the user can upload csv dataset from his local directory....
Sample Dataset:
df
month passengers
1 01-01-2000 2072798
2 01-02-2000 2118150
3 01-03-2000 2384907
4 01-04-2000 2260620
5 01-05-2000 2386165
6 01-06-2000 2635018
7 01-07-2000 2788843
8 01-08-2000 2942082
9 01-09-2000 2477000
10 01-10-2000 2527969
11 01-11-2000 2161170
12 01-12-2000 2175314
13 01-01-2001 2307525
14 01-02-2001 2196415
15 01-03-2001 2545863
library(signal)
library(shiny)
library(AnomalyDetection) #devtools::install_github("twitter/AnomalyDetection")
library(ggplot2)
# Define UI for application that draws a histogram
library(shinydashboard)
library(shinycssloaders)
library(googleVis)
shinyUI(dashboardPage(skin = "green",
dashboardHeader(title = "Anomaly Detection in Time series",
titleWidth = 350),
dashboardSidebar(
sidebarUserPanel("Nishant Upadhyay",
image = "nishantcofyshop.jpg"
),
sidebarMenu(
menuItem("Data", tabName = "data", icon = icon("database")),
menuItem("Filters", tabName = "filter", icon = icon("filter")),
menuItem("Anomalies", tabName = "anomaly", icon = icon("check")),
#menuItem("Save Data", tabName = "save", icon = icon("save"))
menuItem("About The App", tabName = "Help", icon = icon("info-circle"))
)
),
dashboardBody(
tabItems(
tabItem(tabName = "data",
fluidRow(
box(
title = "Data scatter Chart",
status = "primary",
solidHeader = T,
collapsible = T,
width = 12,
shinycssloaders::withSpinner(htmlOutput("dataChart"),type = getOption("spinner.type", default = 8),color = "red")
)
),
fluidRow(
box(
radioButtons(
"data_input","",
choices = list("Load sample data" = 1,
"Upload csv file" = 2
)
),
conditionalPanel(
condition = "input.data_input=='1'",
h5("Sample dataset of Lebron James basketball shots over the years")
),
conditionalPanel(
condition = "input.data_input=='2'",
fileInput('file1', 'Choose file to upload',
accept = c(
'text/csv',
'text/comma-separated-values',
'text/tab-separated-values',
'text/plain',
'.csv',
'.tsv'
)),
checkboxInput('header', 'Header', TRUE),
radioButtons('sep', 'Separator',
c(Comma=',',
Semicolon=';',
Tab='\t'),','),
radioButtons('quote', 'Quote',
c('None'='',
'Double Quote'='"',
'Single Quote'="'"),
'')
),
title = "Select Dataset",
status = "info",
solidHeader = T,
collapsible = T
),
box(
title = "Data",
status = "info",
solidHeader = T,
collapsible = T,
shinycssloaders::withSpinner(htmlOutput('contents'),type = getOption("spinner.type", default = 8),color = "red")
)# end of box
)## end of Fluid row
), ## end of tab item
tabItem(
tabName = "filter",
fluidRow(
box(
title = "Data Chart",
status = "primary",
solidHeader = T,
collapsible = T,
width = 12,
shinycssloaders::withSpinner(htmlOutput('dataChartFiltered'),type = getOption("spinner.type", default = 8),color = "red")
)
),
fluidRow(
box(
title = "Filters",
status = "info",
solidHeader = T,
collapsible = T,
width = 4,
radioButtons("filt", NULL,
c("None" = "none",
"Butterworth" = "butt",
"Type-II Chebyshev" = "cheby2")),
submitButton("Filter")
),
box(
title = "Butterworth",
status = "info",
solidHeader = T,
collapsible = T,
width = 4,
textInput("buttern", label = "Filter Order", value = "3"),
textInput("butterf", label = "Critical Frequencies", value = "0.1"),
radioButtons("buttert", "Type",
c("Low-Pass" = "low",
"High-Pass" = "high"))
),
box(
title = "Chebyshev",
status = "info",
solidHeader = T,
collapsible = T,
width = 4,
textInput("chebyn", label = "Filter Order", value = "5"),
textInput("chebyd", label = "dB of Pass Band", value = "20"),
textInput("chebyf", label = "Critical Frequencies", value = "0.2"),
radioButtons("chebyt", "Type",
c("Low-Pass" = "low",
"High-Pass" = "high"))
)
)
)
) ## end of tab items
) ## end of Dashboard
)
)
shinyServer(function(input, output){
dataframe<-reactive({
if (input$data_input == 1) {
tab <- read.csv("df.csv",header = T,stringsAsFactors = F)
} else if (input$data_input == 2) {
inFile <- input$file1
if (is.null(inFile))
return(data.frame(x = "Select your datafile"))
tab = read.csv(inFile$datapath, header = input$header,
sep = input$sep, quote = input$quote)
}
tt <- tryCatch(as.POSIXct(tab[,1]),error=function(e) e, warning=function(w) w)
if (is(tt,"warning") | is(tt,"error")) {
tab$Old = tab[,1]
tab[,1] = as.POSIXct(1:nrow(tab), origin = Sys.time())
} else {
tab[,1] = as.POSIXct(tab[,1])
}
tab
})
output$dataChart <- renderGvis({
if (!is.null(dataframe()))
gvisLineChart(dataframe()[,c(1,2)], xvar = colnames(dataframe())[1], yvar = colnames(dataframe())[2],
options = list(
crosshair.trigger = 'selection',
enableInteractivity = TRUE,
hAxis.maxTextLines = 10,
tooltip.trigger = 'none'
))
})
output$contents <- renderGvis({
if (!is.null(dataframe()))
gvisTable(dataframe(),
options = list(page='enable'))
})
output$dataChartFiltered <- renderGvis({
if (input$filt == "none") {
return(NULL)
} else if (input$filt == "butt") {
bf <- butter(as.numeric(input$buttern), as.numeric(input$butterf), type = input$buttert)
filtered = data.frame(timestamp = dataframe()[,1],
count = as.numeric(filter(bf, dataframe()[,2])))
gvisLineChart(filtered, xvar = colnames(filtered)[1], yvar = colnames(filtered)[2],
options = list(
crosshair.trigger = 'selection',
enableInteractivity = TRUE,
hAxis.maxTextLines = 10,
tooltip.trigger = 'none'
))
} else if (input$filt == "cheby2") {
ch <- cheby2(as.numeric(input$chebyn), as.numeric(input$chebyd),
as.numeric(input$chebyf), type = input$chebyt)
filtered = data.frame(timestamp = dataframe()[,1],
count = as.numeric(filter(ch, dataframe()[,2])))
gvisLineChart(filtered, xvar = colnames(filtered)[1], yvar = colnames(filtered)[2],
options = list(
crosshair.trigger = 'selection',
enableInteractivity = TRUE,
hAxis.maxTextLines = 10,
tooltip.trigger = 'none'
))
}
})
})
The problem i am facing is that once the shiny app is executed , the sample data is loaded properly as the this data is placed in the app folder in the directory (one can use R inbuilt data set or use the data i gave in the start) and subsequently all steps gets executed properly.
But if i want to upload some other csv file from local directory, the upload button selection does not get activated even after selecting it.But,in fact, if one goes to the second menu item in the sidebar panel i.e. filter tab and clicks on the filter button (under Filters box ) and then if i go back to Data menu in the sidebar panel again, i can see that now my upload csv file button has got activated and now i can browse the csv file in local directory and upload the same into the app and now everything works fine.
It seems somewhere the condition that makes the upload file button is not getting active initially when the app opens....
Need help to sort out the issue...Sorry for posting large chunk of code....
conditionalPanel and submitButton do not work well together. Replace your submitButton("Filter") with actionButton("Filter", "").
EDIT:
As per the comment, for the plot to be generated only after the actionButton is clicked you can put output$dataChartFiltered inside observeEvent of Filter with isolate for `input objects as follows:
observeEvent(input$Filter,{
output$dataChartFiltered <- renderGvis({
if (isolate(input$filt) == "none") {
return(NULL)
} else if (isolate(input$filt) == "butt") {
bf <- butter(as.numeric(isolate(input$buttern)), as.numeric(isolate(input$butterf)), type = isolate(input$buttert))
filtered = data.frame(timestamp = dataframe()[,1],
count = as.numeric(filter(bf, dataframe()[,2])))
gvisLineChart(filtered, xvar = colnames(filtered)[1], yvar = colnames(filtered)[2],
options = list(
crosshair.trigger = 'selection',
enableInteractivity = TRUE,
hAxis.maxTextLines = 10,
tooltip.trigger = 'none'
))
} else if (isolate(input$filt) == "cheby2") {
ch <- cheby2(as.numeric(isolate(input$chebyn)), as.numeric(isolate(input$chebyd)),
as.numeric(isolate(input$chebyf)), type = isolate(input$chebyt))
filtered = data.frame(timestamp = dataframe()[,1],
count = as.numeric(filter(ch, dataframe()[,2])))
gvisLineChart(filtered, xvar = colnames(filtered)[1], yvar = colnames(filtered)[2],
options = list(
crosshair.trigger = 'selection',
enableInteractivity = TRUE,
hAxis.maxTextLines = 10,
tooltip.trigger = 'none'
))
}
})
})
Related
new to shiny, I am developing a dynamic application for several users.
(Pages should be displayed according to user credentials)
I thought about doing it with the conditionpanel.
but i have this error: agAssert: Expected an object with class 'shiny.tag'
my questions are: can we put sidebar or dashbarbody in conditionpanel? if this is possible how?
and do you have other proposals or approaches? Thank you
below is my code:
# Shiny dashboard project
# TIDE 2021-2022
# global option for sipnners
options(spinner.color="#0275D8", spinner.color.background="#ffffff", spinner.size=2)
# Define dashboardHeader()
header <- dashboardHeader(title = "GOUZOU",
dropdownMenu(
type = "notifications",
headerText = strong("HELP"),
icon = icon("question"),
badgeStatus = NULL,
notificationItem(
text = "Faire une demande de Geste Commercial",
icon = icon("spinner")
)
),
tags$li(class="dropdown",
tags$a(href="http://icx.gan.fr/icx/ActionXMLAppel.do",
icon("github"),
"A propos d'ICX",
target="_blank")
)
) #close header
ui_first <- fluidPage(
useShinyjs(), #set up shinyjs
sidebarLayout(
shinyjs::hidden(
div(id = "Siderbar", sidebarPanel(
conditionalPanel(
condition = "input.tabselected > 1",
# Define dashboardSidebar()
dashboardSidebar(
sidebarMenu(
menuItem("Demande", tabName = "do_demande",
menuItem("Mouvements", tabName = "mouvement", icon = icon("spinner")),
menuItem("Mutualisation", tabName = "do_mutualisation", icon= icon("spinner")),
menuItem("Avance", tabName = "do_avance", icon= icon("spinner")),
menuItem("PEDA", tabName = "do_peda", icon= icon("spinner"))
),
badgeLabel =icon("info-circle"), badgeColor = "light-blue",
menuItem("Validation", icon = icon("th"), tabName = "do_validation",
badgeLabel =icon("database"),
badgeColor = "light-blue"),
menuItem("Chargement", icon = icon("trophy"), tabName = "do_chargement",
badgeLabel =icon("sort-amount-up"),
badgeColor = "light-blue"),
menuItem("Autres", icon = icon("eye"), tabName = "autres",
badgeLabel =icon("chart-bar"),
badgeColor = "light-blue") )
) #close sidebar
) #conditionpanel
) #close siderbarpanel
) #close div
), #close hidden
# Main-Panel ------
mainPanel(
tabsetPanel(
# > Login -------
tabPanel("Login",
value = 1,
br(),
textInput("username", "Nom utilisateur"),
passwordInput("password", label = "GJ utilisateur"),
# If you want to add custom javascript messages
# tags$head(tags$script(src = "message-handler.js")),
actionButton("login", "Login"),
textOutput("pwd")
), # closes tabPanel
id = "tabselected", type = "pills"
) # closes tabsetPanel
) # closes mainPanel
) #close sidebarLayout
) #close fluidePage ui first
# Define dashboardBody()
body <- dashboardBody(
# Found at https://stackoverflow.com/questions/40985684/r-shiny-present-a-shinybs-modal-popup-on-page-visit-no-user-action
# bsModal("window", "Window",
# title="Project Details", size="large",
# h4("English", align = "justify"),
# h5(description_eng, align = "justify"),
# #h4("", align = "justify"),
# h4("French", align = "justify"),
# h5(description_fr, align = "justify"),
# #footer = h4(actionLink('create_account',),align='center'),
# tags$head(tags$style("#window .modal-footer{display:bloc}
# .modal-header .close{display:none}"),
# tags$script("$(document).ready(function(){
# $('#window').modal();
# });")
# )
# ),
tabItems(
tabItem("mouvement",
# Row srtucture
fluidRow(
column(4,
# Define User inputs
selectInput("ag_file1",
label = "choisir une agence",
choices = code_ag,
selected = NULL
),
selectInput("motifs_mouv",
label = "Choisir un motif",
choices = motifs_mouv,
selected = NULL
),
selectInput("enveloppe_mouv",
label = "Choisir une enveloppe",
choices = ""
),
textOutput("founds"),
selectInput("transaction", label = "Debit ou Credit", choices = c("Debit", "Credit")
),
numericInput("montant", label = "saisir le montant(€)" ,
value = "" ,min = 5, max=50000 )
,
actionBttn("soumettre_mouv",
"Soumettre", icon=NULL, style = "unite", color = "success",
size="md", block = FALSE, no_outline = TRUE)
),
column(8,
uiOutput("infos_mouv"))
)
)
,
tabItem("do_mutualisation",
# Row srtucture
fluidPage( tabsetPanel(
tabPanel("Mutualisation entre enveloppes",
selectInput("agence_mut",
label = "veuillez selectionner une agence",
choices = "",
selected = NULL),
selectInput("env_mutu_deb",
label = "sectionner l'enveloppe à debiter",
choices = c("N500", "N600"), selected = NULL),
selectInput("env_mutu_deb",
label = "selectionner l'enveloppe à crediter",
choices = c("N500", "N600") ,
selected = NULL
),
numericInput("montant_mutu",
label = "Saisir le montant",
value = "",
min = 0,
max= Inf),
bsButton("valider_mutu",
label = "Soumettre",
icon = icon("spinner"),
style = "success")
),
tabPanel("mutualisation entre agences",
column(4,
selectInput(
"Code_agence",
label = "Selctionner le code d' l'agence à debiter",
choices = "",
selected = NULL
),
checkboxGroupInput("env_mut_ag_deb",
label = "cocher l'enveloppe à debiter",
choices = c("N500", "N600"),
width = 5)
),
column(10,
selectInput("code_agence",
label = "selectionner le code de l'agence à crediter",
choices = ""),
checkboxGroupInput("env_mut_ag_deb",
label = "cocher l'enveloppe à crediter",
choices = c("N500", "N600"),
width = 5)
,
bsButton("valider_mutu_ag",
label = "Soumettre",
icon = icon("spinner"),
style = "success"),
column(6,
numericInput("mont_mutu_ag",
label = "saisir le montant",
value = "",
min= 5, max = 50000
),
)
),
)
)
)
)
,
tabItem("do_avance",
fluidRow(
column(4,
selectInput("ag_file2",
label = "choisir une agence",
choices = "",
selected = NULL),
selectInput('motifs_avance',
'Selctionnez le motif',
choices = motifs_avance,
selected = "AVANCE SUR CONTRAT"),
selectInput("enveloppe_avance",
"Selectionner une enveloppe",
choices = "",
selected = NULL),
numericInput("montant_avance",
"Saisir le montant de l'avance demandée ou à recuperer",
value = "",
min = 0, max = Inf
),
actionBttn("soumettre_avance",
"Soumettre", icon=NULL, style = "unite", color = "success",
size="md", block = FALSE, no_outline = TRUE)
)
)
),
tabItem("do_validation"
#fluidPage(
# fluidRow(
# column(4,
# selectInput("tab_fil1",
# label = "Filter Select",
# choices = c("Country","Language", "Genre")
# )
#),#
# column(4,
# selectInput("tab_fil2",
# label = "",
# choices = "")
# ),
# column(4,
# numericInput("tab_fil3",
# label = "Number of observations",
# min = 0,
# max = Inf,
# value = 50
# )
# )
# ),
# textOutput("founds2"),
# dataTableOutput("data_view") %>% withSpinner(type = 6)
# )
),
tabItem("do_chargement"
#fluidPage(
# fluidRow(
# column(6,
# selectInput("HOF_fil1",
# label = "Select filter below",
# choices = c("Decade", "Genre", "Year")
#)
#),
#column(6,
# selectInput("HOF_fil2",
# label = "",
# choices = "")
#)
#),
#fluidRow(
# uiOutput("podium_table")
#)
#)
),
tabItem("autres"
#fluidPage(
#fluidRow(
# column(6,
#
# pickerInput(
# inputId = "dec_fil1",
# label = "Select decade below",
# choices = dec_val,
# multiple = FALSE,
# choicesOpt = list(
# disabled = dec_val %in% dec_val[1:2]
# )
# )
# ),
# column(6,
# verbatimTextOutput("cont")
# )
# ),
# fluidRow(
# plotOutput("countTitleGraph",width = "70%") %>% withSpinner(type = 6)
# )
)
)
) #close body
footer <- dashboardFooter(
left = "Gan",
right = "contact:"
)
# ui out to server
ui<-dashboardPagePlus(header, ui_first, body, footer=footer)
#server :
server <- function(input, output, session) {
user_vec <- c("niang" = "GJ7471",
"gouzou" = "PL4350")
# I usually do run the code below on a real app on a server
# user <- reactiveValues(his = readRDS(file = "logs/user_his.rds"),
# log = readRDS(file = "logs/user_log.rds"),
# vec = readRDS(file = "logs/user_vec.rds"))
#
# where user_his is defined as follows
# user_his <- vector(mode = "integer", length = length(user_vec))
# names(user_his) <- names(user_vec)
observeEvent(input$login, {
if (str_to_lower(input$username) %in% names(user_vec)) { # is username in user_vec?
# Alternatively if you want to limit login attempts to "3" using the user_his file
# if (str_to_lower(input$username) %in% names(user$vec[user$his < 3])) {
if (input$password == unname(user_vec[input$username])) {
# nulls the user_his login attempts and saves this on server
# user$his[str_to_lower(input$username)] <- 0
# saveRDS(user$his, file = "logs/user_his.rds")
# Saves a temp log file
# user_log_temp <- data.frame(username = str_to_lower(input$username),
# timestamp = Sys.time())
# saves temp log in reactive value
# user$log <- rbind(user$log, user_log_temp)
# saves reactive value on server
# saveRDS(user$log, file = "logs/user_log.rds")
# > Add MainPanel and Sidebar----------
shinyjs::show(id ="Siderbar")
appendTab(inputId = "tabselected",
tabPanel("Tab 1",
value = 2
) # closes tabPanel,
)
appendTab(inputId = "tabselected",
tabPanel("Tab 2",
value = 3
) # closes tabPanel,
)
appendTab(inputId = "tabselected",
tabPanel("Tab 3",
value = 4
) # closes tabPanel
)
removeTab(inputId = "tabselected",
target = "1")
} else { # username correct, password wrong
# adds a login attempt to user_his
# user$his[str_to_lower(input$username)] <- user$his[str_to_lower(input$username)] + 1
# saves user_his on server
# saveRDS(user$his, file = "logs/user_his.rds")
# Messge which shows how many log-in tries are left
#
# session$sendCustomMessage(type = 'testmessage',
# message = paste0('Password not correct. ',
# 'Remaining log-in tries: ',
# 3 - user$his[str_to_lower(input$username)]
# )
# )
} # closes if-clause
} else { # username name wrong or more than 3 log-in failures
# Send error messages with javascript message handler
#
# session$sendCustomMessage(type = 'testmessage',
# message = paste0('Wrong user name or user blocked.')
# )
} # closes second if-clause
}) # closes observeEvent
#demande
######### Server Mouvement
observeEvent(
input$motifs_mouv,
updateSelectInput(session,
inputId = "enveloppe_mouv",
label = "Choisir une enveloppe",
choices = enveloppeChoices()
)
)
enveloppeChoices <- reactive({
MOUVEMENT$ENVELOPPES[MOUVEMENT$MOTIFS == input$motifs_mouv] %>% sort()
})
output$founds <- reactive({
paste(MOUVEMENT$ENVELOPPES[MOUVEMENT$MOTIFS == input$motifs_mouv] %>% length(), "enveloppe(s) trouvrées")
})
# filtering data and rendering to htmlTable
output$infos_mouv <- renderUI({
table(
code_agence = input$ag_file1,
titulaires = TABLEICX$TITULAIR[TABLEICX$CODEICX == input$ag_file1],
reseau = TABLEICX$RESEAU[TABLEICX$CODEICX == input$ag_file1],
region = TABLEICX$REGION[TABLEICX$CODEICX== input$ag_file1],
telephone= TABLEICX$TEL[TABLEICX$CODEICX== input$ag_file1],
ICRA= TABLEICX$NOMICRA[TABLEICX$CODEICX == input$ag_file1],
DCR= TABLEICX$NOMDR[TABLEICX$CODEICX == input$ag_file1],
email= TABLEICX$EMAIL[TABLEICX$CODEICX == input$ag_file1]
)
})
observeEvent(input$soumettre_mouv, {
log <- data.frame(
Demandeur = TABLEICX$TITULAIR[TABLEICX$CODEICX == input$ag_file1],
Code = input$ag_file1,
Motif = input$motifs_mouv,
enveloppe = input$enveloppe_mouv,
Date = Sys.time(),
transaction = input$transaction,
montant = input$montant
)
write.table(log,
file = "logs.table",
sep = ";",
append = TRUE,
row.names = FALSE,
col.names = FALSE)
sendSweetAlert(
session = session,
title = "Recapitulatif de votre demande",
text = fluidRow(
column(12,
uiOutput("demande_details"),
style= "font-size: 9pt"
),
column(
width = 12,
DT::DTOutput("logs_table"),
style = "font-size: 8pt"
#tableOutput("logs_table")
),
column(
width=12,
actionBttn("valider_mouv", "Valider", icon=NULL, style = "unite", color = "success",
size="md", block = FALSE, no_outline = TRUE
)
)
),
# style = "margin-top: 50px"
html = TRUE
)
})
logs <- eventReactive(input$soumettre_mouv, {
if (file.exists("logs.table")) {
Sys.sleep(2)
read.table(
"logs.table",
sep = ";",
colClasses = "character",
col.names = c("Demandeur", "Code", "Motif", "enveloppe","Date","transaction", "montant")
)
}
} %>%
arrange(desc(Date), .by_group= FALSE) %>% head(1)
, ignoreNULL = FALSE)
output$demande_details <- renderUI({
req(logs())
tagList(
h4(logs()$Code),
p(paste("Vous allez faire une demander de ", input$transaction," ", "pour le motif " ," ", logs()$Motif, " ", "sur votre enveloppe ", logs()$enveloppe )
)
)
})
output$logs_table <- DT::renderDT({
req(logs())
logs() %>%
select(Demandeur, enveloppe, montant, Date) %>%
DT::datatable(
options = list(pageLength = 10, responsive = TRUE, dom = "tp"),
selection = "single",
class = "display compact",
rownames = FALSE
)
})
observeEvent(input$valider_mouv,
{
#req(logs())
histo_mouv <- data.frame(
Demandeur = logs()$Demandeur,
Code = logs()$Code,
Motif = logs()$Motif,
Enveloppe = logs()$enveloppe,
Date = logs()$Date,
Transaction = logs()$transaction,
Montant = logs()$montant,
ICRA= TABLEICX$NOMICRA[TABLEICX$CODEICX == input$ag_file1],
DCR= TABLEICX$NOMDR[TABLEICX$CODEICX == input$ag_file1]
)
write.table(histo_mouv,
file = "mouv_histo.table",
sep = ";",
append = TRUE,
row.names = FALSE,
col.names = FALSE)
column(
width = 12,
DT::DTOutput("histo_mouv_table"),
style = "font-size: 8pt"
#tableOutput("logs_table")
)
sendSweetAlert(
session = session,
title = "Validé !",
text = "Votre demande a bien été soumise",
type = "success"
)
}
)
mouv_histo <- eventReactive(input$valider_mouv, {
if (file.exists("mouv_histo.table")) {
Sys.sleep(2)
read.table(
"mouv_histo.table",
sep = ";",
colClasses = "character",
col.names = c("Demandeur", "Code", "Motif", "Enveloppe","Date","Transaction", "Montant","ICRA", "DCR")
)
}
} %>%
arrange(desc(Date), .by_group= FALSE)
, ignoreNULL = FALSE)
output$histo_mouv_table <- DT::renderDT({
req(logs())
mouv_histo() %>%
DT::datatable(
options = list(pageLength = 5, responsive = TRUE, dom = "tp"),
selection = "single",
class = "display compact",
rownames = FALSE
)
})
#Avance server
observeEvent(
input$motifs_avance,
updateSelectInput(session,
inputId = "enveloppe_avance",
label = "Choisir une enveloppe",
choices = enveloppeAvance()
)
)
enveloppeAvance <- reactive({
AVANCE$ENVELOPPES[AVANCE$MOTIFS == input$motifs_avance]
})
# filtering data and rendering to htmlTable
#output$infos_mouv <- renderUI({
# })
# output of the findings length afer user input filter
}
#####################################################################
Thanks for taking your valuable time to pitch in into this question. :-)
I'm building a shiny app that would take user inputs through rhandsontable and save it as a .rds file for data persistence.
The code is as follows:
Global.r
library(shiny)
library(shinydashboard)
library(shinycssloaders
library(rhandsontable)
library(htmltools)
library(plotly)
library(shinyjs)
library(tidyverse)
library(DT)
# Reads the data stored already
raw_data_projects <- readRDS("Projects.rds")
# code to refresh app so as to display the newly added data
jsResetCode <- "shinyjs.reset = function() {history.go(0)}"
ui.R
dashboardPage(skin = "black",
dashboardHeader(dropdownMenuOutput("dropdownmenu"),title = "PMO Dashboard",
tags$li(div(img(src = 'TechM_logo.png',
height = "35px"),
style = "padding-top:10px; padding-bottom:10px;"),
class = "dropdown"),dropdownMenuOutput("msgOutput")) ,
dashboardSidebar(
sidebarMenu(
menuItem("Home", tabName = "home", icon = icon("home")),
menuItem("Projects", tabName = "pros", icon = icon("briefcase")),
menuItem("About Team", tabName = "teamstr", icon = icon("user-friends")),
menuItem("Training & Skills",tabName = "skills",icon = icon("book"))
)),
dashboardBody(
useShinyjs(), # Include shinyjs in the UI
extendShinyjs(text = jsResetCode),
tags$link(rel = "stylesheet", type = "text/css", href = "style_2.css"),
tabItems(
tabItem(tabName = "pros",
fluidPage(tabBox(width = "500px",
tabPanel("Metrics",
fluidRow(
valueBoxOutput("Completed", width = 3),
valueBoxOutput("WIP", width = 3),
valueBoxOutput("Delayed", width = 3),
valueBoxOutput("OnHold", width = 3)
),
fluidRow(
box(plotlyOutput("Project_category"), width = 4,solidHeader = TRUE, status = "primary", title = "Project Category", collapsible = TRUE),
box(plotlyOutput("Project_status"), width = 8,solidHeader = TRUE, status = "primary", title = "Project Status", collapsible = TRUE),
box(plotlyOutput("Complexity"), width = 4,solidHeader = TRUE, status = "primary", title = "Project Complexity", collapsible = TRUE),
box(plotlyOutput("Audits"), width = 4,solidHeader = TRUE, status = "primary", title = "Audit Status", collapsible = TRUE)
)),
tabPanel("Data",
box(withSpinner(rHandsontableOutput("Projects")), width = 12),
actionButton("saveBtnProjects", "Save Projects", icon = icon("save")),
actionButton("BtnResetProjects", "Reset Filters", icon = icon("eraser")))))
)))
server.r
shinyServer(function(input, output, session){
dt_projects <- reactive({ raw_data_projects })
vals <- reactiveValues()
output$Projects <- renderRHandsontable({
rhandsontable(dt_projects(), readOnly = FALSE, search = TRUE, selectCallback = TRUE ) %>%
hot_cols(columnSorting = TRUE, manualColumnMove = TRUE, manualColumnResize = TRUE ) %>%
hot_table(highlightRow = TRUE, highlightCol = TRUE) %>%
#hot_col("PROJECT.STATUS", renderer = text_renderer, type = "autocomplete") %>%
hot_rows(fixedRowsTop = 1)
})
# on click of button the file will be saved to the working directory
observeEvent(input$saveBtnProjects,
#write.csv(hot_to_r(input$Projects), file = "./Data/project_tracker.csv",row.names = FALSE)
saveRDS(hot_to_r(input$Projects),"Projects.rds")
)
# refresh the page
observeEvent(input$saveBtnProjects, {js$reset()})
})
So when I run the app I get the table I desire as below:
As we can see, as I was inserting values to the first column, all the other columns greyed out and I couldn't insert any values into it. Please help me with this issue.
Also please suggest if my code will display the data reactively as soon as I save the data by pressing Save Projects button.
Thanks a ton in advance!!
P.S : I have included the server code only for the table considering the length of the question leaving the code of other tabs. But still this code is reproducible.
I have added multiple select inputs to my shiny app in the sidebar and in the main body and want to create a graph that will change when any of those inputs have been selected or changed but I keep getting the error Warning: Error in : Result must have length 56127, not 0.
UI:
ui <- dashboardPage(
dashboardHeader(title = "Human Trafficking"),
dashboardSidebar(
sidebarMenu(
selectInput("Source", "Choose a Data Source: ", choices = " ", 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 = " "),
actionButton("button", "Apply")
)
),
dashboardBody(
fluidRow(
box(width = 4, solidHeader = TRUE,
selectInput("traffickingType", "Choose a trafficking type: ", choices = " ", selected = NULL,
multiple = TRUE, selectize = TRUE, width = NULL, size = NULL)
),
box(width = 4, solidHeader = TRUE,
selectInput("traffickingSubType", "Choose a trafficking sub type: ", choices = " ", selected = NULL,
multiple = TRUE, selectize = TRUE, width = NULL, size = NULL)
),
box(width = 4, solidHeader = TRUE,
selectInput("gender", "Choose a gender: ", choices = " ", selected = NULL,
multiple = TRUE, selectize = TRUE, width = NULL, size = NULL)
)
),
fluidRow(
box(width = 12,
plotlyOutput('coolplot')
)
)
)
)
Server:
server <- function(input, output, session) {
genderVic = sort(unique(ngo$Victim.Gender))
updateSelectInput(session, "gender", choices = genderVic)
traffickingSub = sort(unique(ngo$Trafficking.Sub.Type))
updateSelectInput(session, "traffickingSubType", choices = traffickingSub)
trafficking = sort(unique(ngo$Trafficking.Type))
updateSelectInput(session, "traffickingType", choices = trafficking)
traffickerNationalities = sort(unique(ngo$Trafficker.Nationality))
updateSelectInput(session, "TraffickerNation", choices = traffickerNationalities)
dataSource = sort(unique(ngo$Data.Provided.By))
updateSelectInput(session, "Source", choices = dataSource)
nationalities = sort(unique(ngo$Victim.Nationality))
updateSelectInput(session, "Nationality", choices = nationalities)
output$coolplot <- renderPlotly({
ngo <-
ngo %>%
filter(Victim.Nationality == input$Nationality,
Victim.Gender == input$gender,
Trafficking.Type == input$traffickingType
)
p = ggplot(ngo, aes(x = Victim.Age, fill = Trafficking.Type)) +
geom_bar(position = "stack")
ggplotly(p) %>%
layout(showlegend = FALSE)
})
}
So currently only have it calling three of the inputs to test it but still getting an error.
It should work after the error is displayed once you select a gender and trafficking type in your example. The reason for the error is that renderPlotly is expecting values for input$traffickingType and input$gender but these start out as NULL.
Add a req for each of those selectInputs:
output$coolplot <- renderPlotly({
ngo <-
ngo %>%
filter(Victim.Nationality == input$Nationality,
Victim.Gender == req(input$gender),
Trafficking.Type == req(input$traffickingType)
)
p = ggplot(ngo, aes(x = Victim.Age, fill = Trafficking.Type)) +
geom_bar(position = "stack")
ggplotly(p) %>%
layout(showlegend = FALSE)
})
I am using library(ygdashboard) from here for build a Right Side control bar in Shiny Apps. Which most like AdminLTE.io template.
In AdminLTE.io Right Side Control Bar there is an option,by enabling it the content part will adjust the width and display accordingly.
Can any body help me out here?? My Try:
Mycode:
UI.R
library(shinydashboard)
library(shinyjs)
library(plotly)
library(shinyWidgets)
library(ygdashboard)
library(c3)
library(flexdashboard)
source("helper.R")
dashboardPage( skin = 'green',
dashboardHeader(title=" Test Stand Report",
tags$li(a(img(src = 'logo.jfif',
height = "30px"),
style = "padding-top:10px; padding-bottom:10px;"),
class = "dropdown")),
dashboardSidebar(sidebarMenu(id="tabs",
menuItem("DashBoard", tabName = "dashboard", icon = icon("dashboard", lib = "glyphicon")),
menuItem("Drill Report",icon = icon("link",lib = "glyphicon"),
menuSubItem("Test Stand",tabName = "test_stand",icon = icon("database")),
menuSubItem("Test Code",tabName = "test_code",icon = icon("folder-open",lib = "glyphicon")),
menuSubItem("Product Based",tabName = "product_based",icon = icon("database")),
menuSubItem("Time Shift",tabName = "time_shift",icon = icon("folder-open",lib = "glyphicon"))
)
)
),
dashboardBody(
shinyjs::useShinyjs(),
tabItems(
tabItem(tabName = "dashboard",
fluidRow(
column(3,
gaugeOutput("gauge1",width = "100%", height = "auto"),
uiOutput("infobox_1")
#gaugeOutput("gauge2",width = "100%", height = "auto")
),
column(3,
gaugeOutput("gauge3",width = "100%", height = "auto"),
uiOutput("infobox_2")
#gaugeOutput("gauge4",width = "100%", height = "100px")
),
column(3,
gaugeOutput("gauge5",width = "100%", height = "auto"),
uiOutput("infobox_3")
#gaugeOutput("gauge6",width = "100%", height = "auto")
),
column(3,
gaugeOutput("gauge7",width = "100%", height = "auto"),
uiOutput("infobox_4")
#gaugeOutput("gauge8",width = "100%", height = "auto")
)
),
fluidRow(
)
),
tabItem(tabName = "test_stand",
fluidRow(
column(3,
wellPanel(
uiOutput("test_stand_select")
)
),
column(3,uiOutput("count_test_code")),
column(3,uiOutput("count_vehicle_tested")),
column(3,uiOutput("count_vehicle_failed"))
),
fluidRow(
box(title = "Success Faliure Ratio",solidHeader = TRUE,width = 4,collapsible = TRUE,height = 'auto',status="success",
plotlyOutput("sucess_faliure_pie",height = '250px')
#tableOutput("sucess_faliure_pie")
),
box(title = "Success Faliure rate with Test_Code",solidHeader = TRUE,width = 8,collapsible = TRUE,height = 'auto',status="success",
#tableOutput("test_stand_test_code_rel")
plotlyOutput("test_stand_test_code_rel",height = '250px')
)
)
),
tabItem(tabName = 'test_code',
fluidRow(
)
)
)
),
dashboardFooter(mainText = "My footer", subText = "2018"),
dashboardControlbar()
)
Server.R
library(shiny)
library(shinyjs)
library(RMySQL)
library(DT)
library(devtools)
library(woe)
library(sqldf)
library(plyr)
library(shinyalert)
source("helper.R")
shinyServer(function(input, output,session) {
######################### Date range Selection ################################
output$date_range<-renderUI({
if(input$tabs=="test_stand")
{
dateRangeInput("selected_date_range_test_stand", "Select Time Period:",
start = Sys.Date()-10,
end = Sys.Date(),
max=Sys.Date())
}
else if(input$tabs=="test_code")
{
dateRangeInput("selected_date_range_test_code", "Select Time Period:",
start = Sys.Date()-10,
end = Sys.Date(),
max=Sys.Date())
}
else if(input$tabs=="product_based")
{
dateRangeInput("selected_date_range_product_based", "Select Time Period:",
start = Sys.Date()-10,
end = Sys.Date(),
max=Sys.Date())
}
})
##########################report buttom ################################
output$action_btn<-renderUI({
if(input$tabs=="test_stand")
{
actionBttn("get_data_test_stand","Get Report")
}
else if(input$tabs=="test_code")
{
actionBttn("get_data_test_code","Get Report")
}
else if(input$tabs=="product_based")
{
actionBttn("get_data_product_based","Get Report")
}
})
#########################product group selection##################################
output$pg_list<-renderUI({
if(input$tabs=="test_stand")
{
selectInput("selected_pg_test_stand","Select your Product Group",choices = c("Back"="BHO","SKD"="SKD","ABC"="ABC"))
}
else if(input$tabs=="test_code")
{
selectInput("selected_pg_test_code","Select your Product Group",choices = c("Back"="BHO","SKD"="SKD","ABC"="ABC"))
}
else if(input$tabs=="product_based")
{
selectInput("selected_pg_product_based","Select your Product Group",choices = c("Back"="BHO","SKD"="SKD","ABC"="ABC"))
}
})
#############################top 8 gauge################################
output$gauge1<-renderGauge({
gauge(0.5,
min = 0,
max = 1,
sectors = gaugeSectors(success = c(0.5, 1),
warning = c(0.3, 0.5),
danger = c(0, 0.3)),label = 'Gauge 1')
})
output$infobox_1<-renderInfoBox({
infoBox("Total Test Stand Active",10 * 2,subtitle = "Subtitle", icon = icon("credit-card"),fill = TRUE,color = "yellow")
})
output$gauge3<-renderGauge({
gauge(0.7,
min = 0,
max = 1,
sectors = gaugeSectors(success = c(0.5, 1),
warning = c(0.3, 0.5),
danger = c(0, 0.3)),label = 'Gauge 3')
})
output$infobox_2<-renderInfoBox({
infoBox("Total Test Code Running ",10 * 2,subtitle = "Subtitle" ,icon = shiny::icon("bar-chart"),color = "fuchsia",width = 4,fill = TRUE)
})
output$gauge5<-renderGauge({
gauge(0.6,
min = 0,
max = 1,
sectors = gaugeSectors(success = c(0.5, 1),
warning = c(0.3, 0.5),
danger = c(0, 0.3)),label = 'Gauge 5')
})
output$infobox_3<-renderInfoBox({
infoBox(
"Total Vehicle Tested", "80%",subtitle = "Subtitle", icon = icon("list"),
color = "green", fill = TRUE
)
})
output$gauge7<-renderGauge({
gauge(0.3,
min = 0,
max = 1,
sectors = gaugeSectors(success = c(0.5, 1),
warning = c(0.3, 0.5),
danger = c(0, 0.3)),label = 'Gauge 7')
})
output$infobox_4<-renderInfoBox({
infoBox("Total Vehicle Passed ",10 * 2,subtitle = "Subtitle", icon = icon("check"),fill = TRUE, color = 'orange')
})
#############################test_stand value_box########################
})
Helper.R (from the link)
dashboardControlbar <- function() {
withTags(
div(
id = "right_sidebar",
# Control Sidebar Open
aside(class = "control-sidebar control-sidebar-dark",
# # # # # # # #
#
# Navigation tabs
#
# # # # # # # #
ul(class = "nav nav-tabs nav-justified control-sidebar-tabs",
# first tabs
li(class = "active",
a(href = "#control-sidebar-first-tab", `data-toggle` = "tab",
i(class = "fa fa-sliders")
)
),
# second tabs
li(
a(href = "#control-sidebar-second-tab", `data-toggle` = "tab",
i(class = "fa fa-search")
)
),
# third tab
li(
a(href = "#control-sidebar-third-tab", `data-toggle` = "tab",
i(class = "fa fa-paint-brush")
)
)
),
# # # # # # # #
#
# Tab Panels
#
# # # # # # # #
div(class = "tab-content",
#########################
# First tab content #
#########################
div(class = "tab-pane active", id = "control-sidebar-first-tab",
h3(class = "control-sidebar-heading", "Controller"),
# write elements here
uiOutput("date_range"),
#textOutput("date_validate"),
uiOutput("pg_list"),
uiOutput("action_btn")
#actionBttn("get_data","Get Report")
),
#########################
# Second tab content #
#########################
div(class = "tab-pane", id = "control-sidebar-second-tab",
h3(class = "control-sidebar-heading", "Search"),
# write other elements here
selectInput("selected_search_topic","Select Content Type to Seacrh",choices = c("Test Stand","Test Code","Product")),
searchInput("searchtext","Enter your Search Topic Here", placeholder = "A placeholder",btnSearch = icon("search"),btnReset = icon("remove"))
),
#########################
# Third tab content #
#########################
div(class = "tab-pane", id = "control-sidebar-third-tab",
# third tab elements here
radioButtons("dist", "Distribution type:",
c("Normal" = "norm",
"Uniform" = "unif",
"Log-normal" = "lnorm",
"Exponential" = "exp")
)
)
)
),
# control-sidebar
# Add the sidebar background. This div must be placed
# immediately after the control sidebar
div(class = "control-sidebar-bg", "")
)
)
}
EDIT: I have simplified the application and make it all the code reproducible.
EDIT 2: I just discovered that when I use the navBarPage I must click on Additional Parameters -> Colour. Then is coloured as expected.
I'm developing a shiny app which filters my genes and then plots a heatmap of the remaining genes. Recently, I have found shinyHeatmaply package. I have download their global, UI and Server, and when I try it on my own computer they work as expected. Unfortunately, when I try to combine my filter app and their heatmap using navbarPage, the last one is not rending properly.
I have created a minimalist example adding the shinyheatmap to the second tabPanel of navbarPage in the https://shiny.rstudio.com/gallery/shiny-theme-selector.html app, but I get the same grey render anyway.
Same mistake in a simpler application
The UI:
Navbar 1 belongs to the shinytheme application, whilst the content of Navbar 2 belongs to the shinyheatmaply
tagList(
shinythemes::themeSelector(),
navbarPage(
# theme = "cerulean", # <--- To use a theme, uncomment this
"shinythemes",
tabPanel("Navbar 1",
sidebarPanel(
fileInput("file", "File input:"),
textInput("txt", "Text input:", "general"),
sliderInput("slider", "Slider input:", 1, 100, 30),
tags$h5("Deafult actionButton:"),
actionButton("action", "Search"),
tags$h5("actionButton with CSS class:"),
actionButton("action2", "Action button", class = "btn-primary")
),
mainPanel(
tabsetPanel(
tabPanel("Tab 1",
h4("Table"),
tableOutput("table"),
h4("Verbatim text output"),
verbatimTextOutput("txtout"),
h1("Header 1"),
h2("Header 2"),
h3("Header 3"),
h4("Header 4"),
h5("Header 5")
),
tabPanel("Tab 2", "This panel is intentionally left blank"),
tabPanel("Tab 3", "This panel is intentionally left blank")
)
)
),
tabPanel("Navbar 2",
fluidPage(
sidebarLayout(
sidebarPanel(width=4,
h4('Data Selection'),
fileInput(inputId="mydata", label = "Import Data",multiple = T),
uiOutput('data'),
checkboxInput('showSample','Subset Data'),
conditionalPanel('input.showSample',uiOutput('sample')),
hr(),h4('Data Preprocessing'),
column(width=4,selectizeInput('transpose','Transpose',choices = c('No'=FALSE,'Yes'=TRUE),selected = FALSE)),
column(width=4,selectizeInput("transform_fun", "Transform", c(Identity=".",Sqrt='sqrt',log='log',Scale='scale',Normalize='normalize',Percentize='percentize',"Missing values"='is.na10', Correlation='cor'),selected = '.')),
uiOutput('annoVars'),
br(),hr(),h4('Row dendrogram'),
column(width=6,selectizeInput("distFun_row", "Distance method", c(Euclidean="euclidean",Maximum='maximum',Manhattan='manhattan',Canberra='canberra',Binary='binary',Minkowski='minkowski'),selected = 'euclidean')),
column(width=6,selectizeInput("hclustFun_row", "Clustering linkage", c(Complete= "complete",Single= "single",Average= "average",Mcquitty= "mcquitty",Median= "median",Centroid= "centroid",Ward.D= "ward.D",Ward.D2= "ward.D2"),selected = 'complete')),
column(width=12,sliderInput("r", "Number of Clusters", min = 1, max = 15, value = 2)),
#column(width=4,numericInput("r", "Number of Clusters", min = 1, max = 20, value = 2, step = 1)),
br(),hr(),h4('Column dendrogram'),
column(width=6,selectizeInput("distFun_col", "Distance method", c(Euclidean="euclidean",Maximum='maximum',Manhattan='manhattan',Canberra='canberra',Binary='binary',Minkowski='minkowski'),selected = 'euclidean')),
column(width=6,selectizeInput("hclustFun_col", "Clustering linkage", c(Complete= "complete",Single= "single",Average= "average",Mcquitty= "mcquitty",Median= "median",Centroid= "centroid",Ward.D= "ward.D",Ward.D2= "ward.D2"),selected = 'complete')),
column(width=12,sliderInput("c", "Number of Clusters", min = 1, max = 15, value = 2)),
#column(width=4,numericInput("c", "Number of Clusters", min = 1, max = 20, value = 2, step = 1)),
br(),hr(), h4('Additional Parameters'),
column(3,checkboxInput('showColor','Color')),
column(3,checkboxInput('showMargin','Layout')),
column(3,checkboxInput('showDendo','Dendrogram')),
hr(),
conditionalPanel('input.showColor==1',
hr(),
h4('Color Manipulation'),
uiOutput('colUI'),
sliderInput("ncol", "Set Number of Colors", min = 1, max = 256, value = 256),
checkboxInput('colRngAuto','Auto Color Range',value = T),
conditionalPanel('!input.colRngAuto',uiOutput('colRng'))
),
conditionalPanel('input.showDendo==1',
hr(),
h4('Dendrogram Manipulation'),
selectInput('dendrogram','Dendrogram Type',choices = c("both", "row", "column", "none"),selected = 'both'),
selectizeInput("seriation", "Seriation", c(OLO="OLO",GW="GW",Mean="mean",None="none"),selected = 'OLO'),
sliderInput('branches_lwd','Dendrogram Branch Width',value = 0.6,min=0,max=5,step = 0.1)
),
conditionalPanel('input.showMargin==1',
hr(),
h4('Widget Layout'),
column(4,textInput('main','Title','')),
column(4,textInput('xlab','X Title','')),
column(4,textInput('ylab','Y Title','')),
sliderInput('row_text_angle','Row Text Angle',value = 0,min=0,max=180),
sliderInput('column_text_angle','Column Text Angle',value = 45,min=0,max=180),
sliderInput("l", "Set Margin Width", min = 0, max = 200, value = 130),
sliderInput("b", "Set Margin Height", min = 0, max = 200, value = 40)
)
),
mainPanel(
tabsetPanel(
tabPanel("Heatmaply",
tags$a(id = 'downloadData', class = paste("btn btn-default shiny-download-link",'mybutton'), href = "", target = "_blank", download = NA, icon("clone"), 'Download Heatmap as HTML'),
tags$head(tags$style(".mybutton{color:white;background-color:blue;} .skin-black .sidebar .mybutton{color: green;}") ),
plotlyOutput("heatout",height='600px')
),
tabPanel("Data",
DT::dataTableOutput('tables')
)
)
)
)
)
),
tabPanel("Navbar 3", "This panel is intentionally left blank")
)
)
The server:
Regarding to the server, first two output correspond to the shinytheme and the others belong to shinyheatmaply
d=data(package='datasets')$results[,'Item']
d=d[!grepl('[\\()]',d)]
d=d[!d%in%c('UScitiesD','eurodist','sleep','warpbreaks')]
d=d[unlist(lapply(d,function(d.in) eval(parse(text=paste0('ncol(as.data.frame(datasets::',d.in,'))')))))>1]
d=d[-which(d=='mtcars')]
d=c('mtcars',d)
server <- shinyServer(function(input, output,session) {
####This to output belongs to the shinytheme application####
output$txtout <- renderText({
paste(input$txt, input$slider, format(input$date), sep = ", ")
})
output$table <- renderTable({
head(cars, 4)
})
#######################################################
#Up to here the code belongs to shinyheatmaply
output$txtout <- renderText({
paste(input$txt, input$slider, format(input$date), sep = ", ")
})
output$table <- renderTable({
head(cars, 4)
})
TEMPLIST<-new.env()
TEMPLIST$d<-d
#Annotation Variable UI ----
observeEvent(data.sel(),{
output$annoVars<-renderUI({
data.in=data.sel()
NM=NULL
if(any(sapply(data.in,class)=='factor')){
NM=names(data.in)[which(sapply(data.in,class)=='factor')]
}
column(width=4,
selectizeInput('annoVar','Annotation',choices = names(data.in),selected=NM,multiple=T,options = list(placeholder = 'select columns',plugins = list("remove_button")))
)
})
#Sampling UI ----
output$sample<-renderUI({
list(
column(4,textInput(inputId = 'setSeed',label = 'Seed',value = sample(1:10000,1))),
column(4,numericInput(inputId = 'selRows',label = 'Number of Rows',min=1,max=pmin(500,nrow(data.sel())),value = pmin(500,nrow(data.sel())))),
column(4,selectizeInput('selCols','Columns Subset',choices = names(data.sel()),multiple=T))
)
})
})
#Data Selection UI ----
output$data=renderUI({
if(!is.null(input$mydata)) TEMPLIST$d=c(input$mydata$name,TEMPLIST$d)
selData=head(TEMPLIST$d,1)
selectInput("data","Select Data",TEMPLIST$d,selected = selData)
})
#Color Pallete UI ----
output$colUI<-renderUI({
colSel='Vidiris'
if(input$transform_fun=='cor') colSel='RdBu'
if(input$transform_fun=='is.na10') colSel='grey.colors'
selectizeInput(inputId ="pal", label ="Select Color Palette",
choices = c('Vidiris (Sequential)'="viridis",
'Magma (Sequential)'="magma",
'Plasma (Sequential)'="plasma",
'Inferno (Sequential)'="inferno",
'Magma (Sequential)'="magma",
'Magma (Sequential)'="magma",
'RdBu (Diverging)'="RdBu",
'RdYlBu (Diverging)'="RdYlBu",
'RdYlGn (Diverging)'="RdYlGn",
'BrBG (Diverging)'="BrBG",
'Spectral (Diverging)'="Spectral",
'BuGn (Sequential)'='BuGn',
'PuBuGn (Sequential)'='PuBuGn',
'YlOrRd (Sequential)'='YlOrRd',
'Heat (Sequential)'='heat.colors',
'Grey (Sequential)'='grey.colors'),
selected=colSel)
})
#Manual Color Range UI ----
output$colRng=renderUI({
if(!is.null(data.sel())) {
rng=range(data.sel(),na.rm = TRUE)
}else{
rng=range(mtcars) # TODO: this should probably be changed
}
# sliderInput("colorRng", "Set Color Range", min = round(rng[1],1), max = round(rng[2],1), step = .1, value = rng)
n_data = nrow(data.sel())
min_min_range = ifelse(input$transform_fun=='cor',-1,-Inf)
min_max_range = ifelse(input$transform_fun=='cor',1,rng[1])
min_value = ifelse(input$transform_fun=='cor',-1,rng[1])
max_min_range = ifelse(input$transform_fun=='cor',-1,rng[2])
max_max_range = ifelse(input$transform_fun=='cor',1,Inf)
max_value = ifelse(input$transform_fun=='cor',1,rng[2])
a_good_step = 0.1 # (max_range-min_range) / n_data
list(
numericInput("colorRng_min", "Set Color Range (min)", value = min_value, min = min_min_range, max = min_max_range, step = a_good_step),
numericInput("colorRng_max", "Set Color Range (max)", value = max_value, min = max_min_range, max = max_max_range, step = a_good_step)
)
})
#Import/Select Data ----
data.sel=eventReactive(input$data,{
if(input$data%in%d){
eval(parse(text=paste0('data.in=as.data.frame(datasets::',input$data,')')))
}else{
data.in=importSwitch(input$mydata[input$mydata$name%in%input$data,])
}
data.in=as.data.frame(data.in)
# data.in=data.in[,sapply(data.in,function(x) class(x))%in%c('numeric','integer')] # no need for this
return(data.in)
})
#Building heatmaply ----
interactiveHeatmap<- reactive({
data.in=data.sel()
if(input$showSample){
if(!is.null(input$selRows)){
set.seed(input$setSeed)
if((input$selRows >= 2) & (input$selRows < nrow(data.in))){
# if input$selRows == nrow(data.in) then we should not do anything (this save refreshing when clicking the subset button)
if(length(input$selCols)<=1) data.in=data.in[sample(1:nrow(data.in),pmin(500,input$selRows)),]
if(length(input$selCols)>1) data.in=data.in[sample(1:nrow(data.in),pmin(500,input$selRows)),input$selCols]
}
}
}
# ss_num = sapply(data.in,function(x) class(x)) %in% c('numeric','integer') # in order to only transform the numeric values
if(length(input$annoVar)>0){
if(all(input$annoVar%in%names(data.in)))
data.in <- data.in%>%mutate_at(funs(factor),.vars=vars(input$annoVar))
}
ss_num = sapply(data.in, is.numeric) # in order to only transform the numeric values
if(input$transpose) data.in=t(data.in)
if(input$transform_fun!='.'){
if(input$transform_fun=='is.na10'){
updateCheckboxInput(session = session,inputId = 'showColor',value = T)
data.in[, ss_num]=is.na10(data.in[, ss_num])
}
if(input$transform_fun=='cor'){
updateCheckboxInput(session = session,inputId = 'showColor',value = T)
updateCheckboxInput(session = session,inputId = 'colRngAuto',value = F)
data.in=cor(data.in[, ss_num],use = "pairwise.complete.obs")
}
if(input$transform_fun=='log') data.in[, ss_num]= apply(data.in[, ss_num],2,log)
if(input$transform_fun=='sqrt') data.in[, ss_num]= apply(data.in[, ss_num],2,sqrt)
if(input$transform_fun=='normalize') data.in=heatmaply::normalize(data.in)
if(input$transform_fun=='scale') data.in[, ss_num] = scale(data.in[, ss_num])
if(input$transform_fun=='percentize') data.in=heatmaply::percentize(data.in)
}
if(!is.null(input$tables_true_search_columns))
data.in=data.in[activeRows(input$tables_true_search_columns,data.in),]
if(input$colRngAuto){
ColLimits=NULL
}else{
ColLimits=c(input$colorRng_min, input$colorRng_max)
}
distfun_row = function(x) dist(x, method = input$distFun_row)
distfun_col = function(x) dist(x, method = input$distFun_col)
hclustfun_row = function(x) hclust(x, method = input$hclustFun_row)
hclustfun_col = function(x) hclust(x, method = input$hclustFun_col)
p <- heatmaply(data.in,
main = input$main,xlab = input$xlab,ylab = input$ylab,
row_text_angle = input$row_text_angle,
column_text_angle = input$column_text_angle,
dendrogram = input$dendrogram,
branches_lwd = input$branches_lwd,
seriate = input$seriation,
colors=eval(parse(text=paste0(input$pal,'(',input$ncol,')'))),
distfun_row = distfun_row,
hclustfun_row = hclustfun_row,
distfun_col = distfun_col,
hclustfun_col = hclustfun_col,
k_col = input$c,
k_row = input$r,
limits = ColLimits) %>%
layout(margin = list(l = input$l, b = input$b, r='0px'))
p$elementId <- NULL
p
})
#Render Plot ----
observeEvent(input$data,{
output$heatout <- renderPlotly({
if(!is.null(input$data))
interactiveHeatmap()
})
})
#Render Data Table ----
output$tables=DT::renderDataTable(data.sel(),server = T,filter='top',
extensions = c('Scroller','FixedHeader','FixedColumns','Buttons','ColReorder'),
options = list(
dom = 't',
buttons = c('copy', 'csv', 'excel', 'pdf', 'print','colvis'),
colReorder = TRUE,
scrollX = TRUE,
fixedColumns = TRUE,
fixedHeader = TRUE,
deferRender = TRUE,
scrollY = 500,
scroller = TRUE
))
#Clone Heatmap ----
observeEvent({interactiveHeatmap()},{
h<-interactiveHeatmap()
l<-list(main = input$main,xlab = input$xlab,ylab = input$ylab,
row_text_angle = input$row_text_angle,
column_text_angle = input$column_text_angle,
dendrogram = input$dendrogram,
branches_lwd = input$branches_lwd,
seriate = input$seriation,
colors=paste0(input$pal,'(',input$ncol,')'),
distfun_row = input$distFun_row,
hclustfun_row = input$hclustFun_row,
distfun_col = input$distFun_col,
hclustfun_col = input$hclustFun_col,
k_col = input$c,
k_row = input$r,
limits = paste(c(input$colorRng_min, input$colorRng_max),collapse=',')
)
#l=l[!l=='']
l=data.frame(Parameter=names(l),Value=do.call('rbind',l),row.names = NULL,stringsAsFactors = F)
l[which(l$Value==''),2]='NULL'
paramTbl=print(xtable::xtable(l),type = 'html',include.rownames=FALSE,print.results = F,html.table.attributes = c('border=0'))
h$width='100%'
h$height='800px'
s<-tags$div(style="position: relative; bottom: 5px;",
HTML(paramTbl),
tags$em('This heatmap visualization was created using',
tags$a(href="https://github.com/yonicd/shinyHeatmaply/",target="_blank",'shinyHeatmaply'),
Sys.time()
)
)
output$downloadData <- downloadHandler(
filename = function() {
paste("heatmaply-", gsub(' ','_',Sys.time()), ".html", sep="")
},
content = function(file) {
libdir <- paste(tools::file_path_sans_ext(basename(file)),"_files", sep = "")
htmltools::save_html(htmltools::browsable(htmltools::tagList(h,s)),file=file,libdir = libdir)
if (!htmlwidgets:::pandoc_available()) {
stop("Saving a widget with selfcontained = TRUE requires pandoc. For details see:\n",
"https://github.com/rstudio/rmarkdown/blob/master/PANDOC.md")
}
htmlwidgets:::pandoc_self_contained_html(file, file)
unlink(libdir, recursive = TRUE)
}
)
})
#End of Code ----
})
Thanks in advance to the hero who solves this problem.
Best rewards, Daniel.
The problem was a conflict between a conditional panel (which uses js) and the navbar page, for any reason default parameters were not read, thus autocoloring which should be enabled wasn't. I just removed this conditional panel and set always its options.