I've just discovered these amazing packages called argonR and argonDash, but ,unfortunatly, I haven't had succes so far using modules with it. Is it possible?
I've tried to ns it, but it doesnt work. It works locally, but It is not able to change tabs when deployed.
# rm(list = ls())
library(shiny)
library(shinydashboard)
library(argonR)
library(argonDash)
library(magrittr)
library(shinyjs)
# Modules
source("sidebar.R", encoding = "utf8")
source("navbar.R", encoding = "utf8")
source("header.R", encoding = "utf8")
source("footer.R", encoding = "utf8")
source("R/mod_home.R", encoding = "utf8")
source("R/mod_stats.R", encoding = "utf8")
source("R/mod_prob.R", encoding = "utf8")
source("R/mod_stat_econ.R", encoding = "utf8")
source("R/mod_econometria.R", encoding = "utf8")
source("R/mod_ML.R", encoding = "utf8")
source("R/mod_quiz.R", encoding = "utf8")
source("R/mod_sobre.R", encoding = "utf8")
# App
ui <- argonDashPage(
title = "TCM",
author = "Guilherme",
description = "Guig's TCM",
sidebar = argonDashSidebar(
vertical = TRUE,
skin = "light",
background = "white",
size = "md",
side = "left",
id = "my_sidebar",
brand_url = "http://www.google.com",
# brand_logo = "https://demos.creative-tim.com/argon-design-system/assets/img/brand/blue.png",
# brand_logo = ,
brand_logo = "https://kdrt.org/sites/default/files/styles/adaptive/public/Rocket%20Radio%20program%20picture.png?itok=-FHCim8R",
argonSidebarHeader(title = "Menu Principal"),
argonSidebarMenu(
argonSidebarItem(
tabName = "home_tab",
style="text-align:center",
"Home"
),
argonSidebarItem(
tabName = "stats_tab",
style="text-align:center",
"Estatística"
),
argonSidebarItem(
tabName = "prob_tab",
style="text-align:center",
"Probabilidade"
),
argonSidebarItem(
tabName = "stat_econ_tab",
style="text-align:center",
"Estatística Econômica"
),
argonSidebarItem(
tabName = "econometria_tab",
style="text-align:center",
"Econometria"
),
argonSidebarItem(
tabName = "ML_tab",
style="text-align:center",
"Machine Learning"
),
argonSidebarItem(
tabName = "quiz_tab",
style="text-align:center",
"Quiz"
),
argonSidebarItem(
tabName = "sobre_tab",
style="text-align:center",
"Sobre"
)
),
argonSidebarDivider(),
argonSidebarHeader(title = "#TCM Versão 0.1")
),
navbar = argonDashNavbar(
argonDropNav(
title = "Powered by R",
# src = "https://demos.creative-tim.com/argon-dashboard/assets/img/theme/team-4-800x800.jpg",
src = "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcRCLcatfAURCtGHsd71IjruuQqMXjezkwwjZR5inocuNz0imUF5sA",
orientation = "right",
argonDropNavTitle(title = "Este app é formado por"),
argonDropNavItem(
title = "R",
src = "https://www.r-project.org/",
icon = argonIcon("single-02")
),
argonDropNavItem(
title = "RStudio",
src = "https://rstudio.com/",
icon = argonIcon("settings-gear-65")
),
argonDropNavDivider(),
argonDropNavItem(
title = "Guigo's código",
src = "#",
icon = argonIcon("calendar-grid-58")
)
)
),
header = argonDashHeader(
gradient = TRUE,
color = "primary",
separator = TRUE,
separator_color = "secondary"#,
# argonCard(
# title = "Olá, visitante!",
# src = "https://www.linkedin.com/in/guilherme-viegas-1b5b0495/",
# hover_lift = TRUE,
# shadow = TRUE,
# shadow_size = NULL,
# hover_shadow = FALSE,
# border_level = 0,
# # icon = argonIcon("atom"),
# icon = "https://scontent.ffln1-1.fna.fbcdn.net/v/t1.0-9/13669798_1073355219425752_3359245208514920392_n.jpg?_nc_cat=111&_nc_oc=AQk0e2H7_Cjzdx97Vq_sl2v_JrdqSZBK5oFe6Kj6VGu_OKOvO7zFTwta02RVm-Bz8Ck&_nc_ht=scontent.ffln1-1.fna&oh=bad62632b291289b4338d3aec456cbe2&oe=5E2B61E2",
# status = "primary",
# background_color = NULL,
# gradient = FALSE,
# floating = FALSE,
# "Seja muito bem vindo.\nEste é meu cartão, tome."
# )
),
body = argonDashBody(
argonTabItems(
argonTabItem(
tabName = "home_tab",
mod_home_ui("home_ui_1")
),
argonTabItem(
tabName = "stats_tab",
mod_stats_ui("stats_ui_1")
),
argonTabItem(
tabName = "prob_tab",
mod_prob_ui("prob_ui_1")
),
argonTabItem(
tabName = "stat_econ_tab",
mod_stat_econ_ui("stat_econ_ui_1")
),
argonTabItem(
tabName = "econometria_tab",
mod_econometria_ui("econometria_ui_1")
),
argonTabItem(
tabName = "ML_tab",
mod_ML_ui("ML_ui_1")
),
argonTabItem(
tabName = "quiz_tab",
mod_quiz_ui("quiz_ui_1")
),
argonTabItem(
tabName = "sobre_tab",
mod_sobre_ui("sobre_ui_1")
)
)
),
footer = argonDashFooter(
copyrights = "#Guilherme Viegas, 2019",
src = "https://www.linkedin.com/in/guilherme-viegas-1b5b0495/",
argonFooterMenu(
argonFooterItem("Linkedin", src = "https://www.linkedin.com/in/guilherme-viegas-1b5b0495/"),
argonFooterItem("Github", src = "https://github.com/Gui-go"),
argonFooterItem("Facebook", src = "https://www.facebook.com/guilherme.viegas.90"),
argonFooterItem("Instagram", src = "https://demos.creative-tim.com/argon-design-system/index.html")
)
)
)
server <- function(input, output) {
# observeEvent(input$my_sidebar, {
# if (input$my_sidebar != "sobre") {
# updateTabItems(session, inputId = "tabs", selected = "quiz")
# }
# })
callModule(mod_home_server, "home_ui_1")
callModule(mod_stats_server, "stats_ui_1")
callModule(mod_prob_server, "prob_ui_1")
callModule(mod_stat_econ_server, "stat_econ_ui_1")
callModule(mod_econometria_server, "econometria_ui_1")
callModule(mod_ML_server, "ML_ui_1")
callModule(mod_quiz_server, "quiz_ui_1")
callModule(mod_sobre_server, "sobre_ui_1")
}
shinyApp(ui = ui, server = server)
Although It works locally, when I deploy it, It simple doesnt work online. In other words, it works fine locally, but when deplyed it simple doesnt change the tabs. Weird right?
I have found the answer. As for October 2019, the CRAN package version does not allow change of tabs (It's a bug). This error was corrected in their Github package version, and soon will be on CRAN as well. It's just a bug, happens...
you can use modules like this!
I suppose global.R and app.R are in the same directory.
global.R
library(shiny)
library(argonR)
library(argonDash)
app.R
source(file.path("global.R"), local = TRUE)$value
shiny::shinyApp(
ui = argonDashPage(
title = "Argon App",
description = "Your description",
author = "You",
navbar = argonDashNavbar(),
sidebar = argonDashSidebar(
id = "sidebar",
side = "left",
size = "md",
skin = "light",
background = "white",
argonSidebarMenu(
argonSidebarItem(
tabName = "Tab1",
icon = argonIcon(name = "circle-08", color = "success"),
"Tab 1"
),
argonSidebarItem(
tabName = "Tab2",
icon = argonIcon(name = "atom", color = "success"),
"Tab 2"
)
)
),
header = argonDashHeader(),
body = argonDashBody(
argonTabItems(
argonTabItem(
tabName = "Tab1",
argonCard(
status = "primary",
width = 12,
title = "Card 1",
hover_lift = TRUE,
shadow = TRUE,
icon = argonIcon("check-bold"),
src = "#",
"Argon is a great free UI package based on Bootstrap 4
that includes the most important components and features."
)
),
argonTabItem(
tabName = "Tab2",
argonBadge(
text = "My badge",
src = "https://www.google.com",
pill = FALSE,
status = "success"
)
)
)
),
footer = argonDashFooter(copyrights = "Yourself")
),
server = function(input, output, session) {
}
)
The strategy has been fully inspired from https://github.com/daattali/advanced-shiny/tree/master/split-code
Related
I have a shiny app, fully built, that I had built all in one script. Everything was working, the ui, etc. and I wanted to modularize the app to make the code a bit more readable. Now all the plots render on top of each other and I can't figure out why. I've tried using pageContainer, sidbarLayout, sidePanel and mainPanel, fluidPage, fixedPage, etc. and none have worked. I'm also using pagePiling with my main ui, so not sure if that has sometimes to do with it? Any help would be much appreciated!
Please find the full code here: https://github.com/eoefelein/COVID_Business_Recovery_and_Social_Capital/tree/master/socialCapitalEmployment
Here is what my ui code looks like:
ui <- tagList(
pagePiling(
center = TRUE,
sections.color = c("#3333FF", "#E6E6E6"),
menu = c(
"Home" = "home",
"Map" = "map",
"Series" = "ts",
"PCA" = "pca",
"Predict" = "predict",
"About" = "about"
),
pageSectionImage(
center = TRUE,
img = "",
menu = "home",
h1(("title"), class = "header shadow-dark"),
h3(
class = "light footer",
"by",
tags$a("news-r", href = "https://news-r.org", class = "link")
)
),
pageSection(center = TRUE,
menu = "map",
mod_map_ui("map"),
br()),
pageSection(center = TRUE,
menu = "ts",
mod_ts_ui("ts"),
br()),
pageSection(center = TRUE,
menu = "pca",
mod_pca_ui("pca"),
br()),
pageSection(
center = TRUE,
menu = "predict",
mod_predict_ui("predict"),
),
pageSection(
center = TRUE,
menu = "about",
h1("About", class = "header shadow-dark"),
h2(
class = "shadow-light",
tags$a(
"The code",
href = "https://github.com/news-r/fopi.app",
target = "_blank",
class = "link"
),
"|",
tags$a(
"The API",
href = "https://github.com/news-r/fopi",
target = "_blank",
class = "link"
)
),
h3(
class = "light footer",
"by",
tags$a("news-r", href = "https://news-r.org", class = "link")
)
)
)
)
Here is my first module's ui:
mod_map_ui <- function(id) {
ns <- NS(id)
tagList(
fluidPage(
h1("Employment & Social Capital across the U.S by County"),
center = TRUE,
column(9, leafletOutput(ns("map"), height = "100vh")),
column(
3,
shinyWidgets::radioGroupButtons(
inputId = ns("idx"),
label = "Metric",
choices = c(unique(social_indices$name)),
checkIcon = list(yes = icon("ok",
lib = "glyphicon"))
)
)
))
}
And here is my second module's ui:
mod_ts_ui <- function(id) {
ns <- NS(id)
tagList(
fixedPage(
h2("Employment by County", align = "center"),
fixedRow(
column(
4,
selectizeInput(
inputId = ns("dataset"),
label = "Choose a county:",
choices = c(unique(employment["countyfips"])),
multiple = TRUE,
selected = "Travis County, Texas",
options = list(create = TRUE)
)
),
column(
8, (echarts4r::echarts4rOutput(ns("ts_plot")))
)
)
)
)
}
okay, so I fixed it and what I think fixed it was specifying a color for each section:
pagePiling(
center = TRUE,
sections.color = c("#7b959c", "#445768","#b9bdc9","#f6e7ea","#e2e2e2","#1e4356"),
menu = c(
"Home" = "home",
"Map" = "map",
"Series" = "ts",
"PCA" = "pca",
"Predict" = "predict",
"About" = "about"
),
Very strange, but after I did that, each plot presented as it should, in it's own section. Hope this helps someone in the future!
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'm using shinydashboardPlus() to include a timeline in an app I'm developing. I want each timelineItem() icon to change colour depending on whether a stage is marked as complete. When a stage is incomplete, I would like the icon to be grey. When a checkboxInput() is selected, I would like the colour to change to olive.
I have written the server-side logic such that when checkboxInput is FALSE the string 'grey' is returned but when TRUE the string 'olive' is returned. I need to pass this string to the argument color in timelineItem(). I have tried passing the string to the argument using textOutput() but this doesn't work. Any ideas how I can pass the correct colour string to color?
Here's an MRE:
library(shiny)
library(shinyWidgets)
library(shinydashboard)
library(shinydashboardPlus)
ui <- dashboardPagePlus(
header = dashboardHeaderPlus(title = "Quality & Assurance Dashboard"),
sidebar = dashboardSidebar(
),
body = dashboardBody(
fluidRow(
box(width = 9,
title = "Assurance Timeline",
status = "info",
timelineBlock(
timelineEnd(color = "danger"),
timelineLabel("Start", color = "teal"),
timelineItem(
title = "Stage 1",
icon = "gears",
color = textOutput("survey_released_colour"), # Need to paste the correct colour string here
time = "now",
footer = "",
textOutput("survey_released_colour")
)
)
),
box(width = 3,
title = "Stage Sign-Off",
status = "info",
timelineBlock(
timelineEnd(color = "danger"),
timelineLabel("Start", color = "teal"),
timelineItem(
title = "Stage 1",
icon = "gears",
color = "olive",
time = "",
footer = "",
"Check here when Stage 1 complete.",
checkboxInput(inputId = "survey_release", "Surveys Released", value = FALSE, width = NULL)
)
)
)
)
),
)
server <- function(input, output) {
output$survey_released_colour<-renderText({
if (input$survey_release == TRUE){
paste0("olive")
}
else
paste0("grey")
})
}
app<-shinyApp(ui = ui, server = server)
runApp(app, host="0.0.0.0",port=5050, launch.browser = TRUE)
from the basic rules of Shiny you can't use any server component inside ui.R. You can use an condition for changing the color in server side.
My try:
library(shinydashboardPlus)
ui <- dashboardPagePlus(
header = dashboardHeaderPlus(title = "Quality & Assurance Dashboard"),
sidebar = dashboardSidebar(
),
body = dashboardBody(
fluidRow(
box(width = 9,
title = "Assurance Timeline",
status = "info",
uiOutput("timeline")
),
box(width = 3,
title = "Stage Sign-Off",
status = "info",
checkboxInput(inputId = "survey_release", "Surveys Released", value = FALSE, width = NULL)
)
)
)
)
server <- function(input, output) {
output$timeline<-renderUI({
if (input$survey_release == TRUE)
{
timelineBlock(
timelineEnd(color = "danger"),
timelineLabel("Start", color = "teal"),
timelineItem(
title = "Stage 1",
icon = "gears",
#color = textOutput("survey_released_colour"), # Need to paste the correct colour string here
color ='red',
time = "now",
footer = ""
)
)
}
else
{
timelineBlock(
timelineEnd(color = "danger"),
timelineLabel("Start", color = "teal"),
timelineItem(
title = "Stage 1",
icon = "gears",
#color = textOutput("survey_released_colour"), # Need to paste the correct colour string here
color ="green",
time = "now",
footer = ""
)
)
}
})
}
shinyApp(ui, server)
let me know if this helps.
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", "")
)
)
}
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'
))
}
})
})