MenuItem rendered as subItem - r

I have a problem with MenuItem in sidebarMenu. When I add a third MenuItem (RFM) it seems that in ui it renders as a subitem and when i click on that item there's nothing being displayed even if in the server.R there's the corresponding function. Here's a screenshot of the sidebarMenu
ui.R
dashboardPage(
dashboardHeader(title= "Acquisti Clienti CC"),
dashboardSidebar(
h4("Explorer"),
textInput("cluster","Digita un Codice cliente CC:","H01621"),
selectizeInput('categ',label="Seleziona una Categoria Merceologica",
choices=unique(user_clustering$DESC_CAT_MERC),
selected=c("NOTEBOOK","PC","TABLET/PDA"),
options = NULL,
multiple=TRUE),
#uiOutput("checkcluster"),
sidebarMenu(id="menu",
tags$style(".fa-stats {color:#f2f4f4}"),
tags$style(".fa-th-list {color:#f2f4f4}"),
menuItem("Dashboard", tabName = "dashboard",icon = icon("stats",lib = "glyphicon")),
menuItem("Data", tabName = "Data",icon = icon("th-list",lib = "glyphicon")),
menuItem("RFM",tabname="RFM",icon = icon("dashboard",lib = "glyphicon")) ## That's the item I ve just added
)
),
dashboardBody(
tabItems(
tabItem("dashboard",
fluidRow(
#valueBoxOutput("Spesa_Grafico",width=3),
valueBoxOutput("Spesa_Totale"),
#valueBoxOutput("Spesa_Cluster",width=3),
valueBoxOutput("Clienti_Totali")
),
fluidRow(
box(title="Cluster 1",plotlyOutput('plot1'),
fluidRow(column(4,offset=3,DT::dataTableOutput("plot1_data",width = 10)))),
#DT::dataTableOutput("plot1_data",width = 8),
box(title="Cluster 2",plotlyOutput('plot2'),
fluidRow(column(4,offset=3,DT::dataTableOutput("plot2_data",width = 10)))),
#DT::dataTableOutput("plot2_data",width = 8),
box(title="Cluster 3",plotlyOutput('plot3'),
fluidRow(column(4,offset=3,DT::dataTableOutput("plot3_data",width = 10)))),
#DT::dataTableOutput("plot3_data",width = 8),
box(title="Cluster 4",plotlyOutput('plot4'),
fluidRow(column(4,offset=3,DT::dataTableOutput("plot4_data",width = 10))))
#DT::dataTableOutput("plot4_data",width = 8)
)
)
,
tabItem("Data",
DT::dataTableOutput("Data"),
downloadButton("downloadCsv", "Download as CSV")
),
tabItem("RFM",
fluidRow(
box(title="RFM",plotOutput('plot_rfm')))
)
)
)
)
server.R
function(input, output, session) {
# Combine the selected variables into a new data frame
# Radar Chart data
selectedData <- reactive({
categ<-input[["categ"]]
data_plot<- user_clustering_raw %>%filter(DESC_CAT_MERC %in% categ)%>%
group_by(CLUSTER,DESC_CAT_MERC)%>%
dplyr::summarise(VAL_INV=sum(VAL_INV))%>%ungroup()%>%
group_by(CLUSTER)%>%mutate(VAL_INV=VAL_INV/sum(VAL_INV))
return (data_plot)
})
# RFM chart (2nd page....)
selectedData_plot2<-reactive({
clust<-user_clustering_raw[user_clustering_raw$CO_CUST==input$cluster,]$CLUSTER[0]
rfm <- RFM_rec %>%
inner_join(user_clustering_raw%>%select(CO_CUST,CLUSTER)%>%distinct(),by="CO_CUST")%>%
filter(CLUSTER %in% clust)
return (rfm)
})
# Data for summary alongside graph
summary_1<-reactive({
categ<-input[["categ"]]
summary_1<-user_clustering_raw%>%
filter(DESC_CAT_MERC%in% categ)
return (summary_1)
})
# Value box
output$Spesa_Totale <- renderValueBox({
valueBox(
value = prettyNum(round(sum(user_clustering$VAL_INV),0),big.mark=",",decimal.mark = "."),
subtitle = "Spesa Totale",
icon = icon("euro"),width=6
)
})
output$Clienti_Totali <- renderValueBox({
valueBox(
length(unique(user_clustering_raw%>%pull(CO_CUST))),
"Numero Clienti Totali",
icon = icon("users"),width=6
)
})
summary_2<-reactive({
outlier<-data.frame(CO_CUST=attributes(big_outliers),FLAG_OUTLIER=1)
colnames(outlier)<-c("CO_CUST","FLAG_OUTLIER")
data_summary_2<- user_clustering_raw%>%left_join(outlier,by="CO_CUST")%>%
replace_na(list(FLAG_OUTLIER=0))
colnames(data_summary_2)<-c("Codice Cliente", "Categoria Merc.",
"Spesa (EUR)","Cluster","Outlier")
data_summary_2
})
# 1 CLUSTER
output$plot1 <- renderPlotly({
categ<-input[["categ"]]
d1<-selectedData()
d1_clust<-d1%>%filter(DESC_CAT_MERC %in% categ)
d1_clust<-d1_clust%>%filter(CLUSTER==1)
plot_ly(
type = 'scatterpolar',
r = d1_clust$VAL_INV,
theta = d1_clust$DESC_CAT_MERC,
fill = 'toself'
) %>%
layout(
polar = list(
radialaxis = list(
visible = T,
range = c(0,1)
)
),
showlegend = F
)
})
output$plot1_data <- DT::renderDataTable({
plot1_data<-summary_1()
plot1_data<-plot1_data%>%filter(CLUSTER==1)%>%
group_by(DESC_CAT_MERC)%>%
summarise(VAL_INV=sum(VAL_INV),NUMERICA_CLIENTI=n_distinct(CO_CUST))%>%
ungroup()%>%
mutate(VAL_INV_PERC=round(VAL_INV/sum(VAL_INV),3)*100)
plot1_data <- plot1_data[c("DESC_CAT_MERC", "VAL_INV", "VAL_INV_PERC","NUMERICA_CLIENTI")]
colnames(plot1_data)<-c("Cat.Merceologica","Fatturato (EUR)","Fatturato %","Numero Clienti")
DT::datatable(plot1_data,rownames = FALSE,options = list(dom = 't',
columnDefs = list(list(className = 'dt-center', targets = "_all"))))%>%formatCurrency(2:2, '')
})
# 2 CLUSTER
output$plot2 <- renderPlotly({
categ<-input[["categ"]]
d1<-selectedData()
d2_clust<-d1%>%filter(DESC_CAT_MERC %in% categ)
d2_clust<-d2_clust%>%filter(CLUSTER==2)
plot_ly(
type = 'scatterpolar',
r = d2_clust$VAL_INV,
theta = d2_clust$DESC_CAT_MERC,
fill = 'toself',mode="markers"
) %>%
layout(
polar = list(
radialaxis = list(
visible = T,
range = c(0,1)
)
),
showlegend = F
)
})
output$plot2_data <- DT::renderDataTable({
plot2_data<-summary_1()
plot2_data<-plot2_data%>%filter(CLUSTER==2)%>%
group_by(DESC_CAT_MERC)%>%
summarise(VAL_INV=sum(VAL_INV),NUMERICA_CLIENTI=n_distinct(CO_CUST))%>%ungroup()%>%
mutate(VAL_INV_PERC=round(VAL_INV/sum(VAL_INV),3)*100)
plot2_data <- plot2_data[c("DESC_CAT_MERC", "VAL_INV", "VAL_INV_PERC","NUMERICA_CLIENTI")]
colnames(plot2_data)<-c("Cat.Merceologica","Fatturato (EUR)","Fatturato %","Numero Clienti")
DT::datatable(plot2_data,rownames = FALSE,
options = list(dom = 't',
columnDefs = list(list(className = 'dt-center', targets = "_all"))))%>%formatCurrency(2:2, '')
})
# 3 CLUSTER
output$plot3 <- renderPlotly({
categ<-input[["categ"]]
d1<-selectedData()
d3_clust<-d1%>%filter(DESC_CAT_MERC %in% categ)
d3_clust<-d3_clust%>%filter(CLUSTER==3)
plot_ly(
type = 'scatterpolar',
r = d3_clust$VAL_INV,
theta = d3_clust$DESC_CAT_MERC,
fill = 'toself'
) %>%
layout(
polar = list(
radialaxis = list(
visible = T,
range = c(0,1)
)
),
showlegend = F
)
})
output$plot3_data <- DT::renderDataTable({
plot3_data<-summary_1()
plot3_data<-plot3_data%>%filter(CLUSTER==3)%>%
group_by(DESC_CAT_MERC)%>%
summarise(VAL_INV=sum(VAL_INV),
NUMERICA_CLIENTI=n_distinct(CO_CUST))%>%ungroup()%>%
mutate(VAL_INV_PERC=round(VAL_INV/sum(VAL_INV),3)*100)
plot3_data <- plot3_data[c("DESC_CAT_MERC", "VAL_INV", "VAL_INV_PERC","NUMERICA_CLIENTI")]
colnames(plot3_data)<-c("Cat.Merceologica","Fatturato (EUR)","Fatturato %","Numero Clienti")
DT::datatable(plot3_data,rownames = FALSE,options = list(dom = 't',
columnDefs = list(list(className = 'dt-center', targets = "_all"))))%>%
formatCurrency(2:2, '')
})
# 4 CLUSTER
output$plot4 <- renderPlotly({
categ<-input[["categ"]]
d1<-selectedData()
d4_clust<-d1%>%filter(DESC_CAT_MERC %in% categ)
d4_clust<-d4_clust%>%filter(CLUSTER==3)
plot_ly(
type = 'scatterpolar',
r = d4_clust$VAL_INV,
theta = d4_clust$DESC_CAT_MERC,
fill = 'toself'
) %>%
layout(
polar = list(
radialaxis = list(
visible = T,
range = c(0,1)
)
),
showlegend = F
)
})
output$plot4_data <- DT::renderDataTable({
plot4_data<-summary_1()
plot4_data<-plot4_data%>%filter(CLUSTER==4)%>%
group_by(DESC_CAT_MERC)%>%
summarise(VAL_INV=sum(VAL_INV),
NUMERICA_CLIENTI=n_distinct(CO_CUST))%>%
ungroup()%>%mutate(VAL_INV_PERC=round(VAL_INV/sum(VAL_INV),3)*100)
plot4_data <- plot4_data[c("DESC_CAT_MERC", "VAL_INV", "VAL_INV_PERC","NUMERICA_CLIENTI")]
colnames(plot4_data)<-c("Cat.Merceologica","Fatturato (EUR)","Fatturato %","Numero Clienti")
DT::datatable(plot4_data,rownames = FALSE,options = list(dom = 't',
columnDefs = list(list(className = 'dt-center', targets = "_all"))))%>%
formatCurrency(2:2, '')
})
# rfm
output$plot_rfm <- renderPlot({
d<-selectedData_plot2()
adding_point<- d[d$CO_CUST==input$cluster,]
p1 <- ggplot(d,aes(x=FREQ))+
geom_histogram(fill="darkblue",col="white")+
ggtitle("Frequenza Acquisti")+labs(x="Frequenza Acquisti",y="Conteggio")+
geom_point(x=adding_point$FREQ,y=0,col="red",size=4)+
theme(axis.text.x = element_text(angle=45,hjust=1,size=12),
axis.title.x = element_blank(),plot.title = element_text(size=14,face="bold"))
breaks <- pretty(range(d$MONET), n = nclass.FD(d$MONET), min.n = 1)
bwidth <- breaks[2]-breaks[1]
p2 <- ggplot(d,aes(x=round(MONET,0)))+
geom_histogram(fill="darkblue",col="white")+
ggtitle("Valore Monetario Acquisti (EUR)")+labs(x="Valore Monetario",y="Conteggio")+
scale_x_continuous(labels=dollar_format(prefix="€"))+
geom_point(x=adding_point$MONET,y=0,col="red",size=4)+
theme(axis.text.x = element_text(angle=45,hjust=1,size=12),
axis.title.x = element_blank(),plot.title = element_text(size=14,face="bold"))
p3 <- ggplot(d,aes(x=LAST_PURCHASE))+
geom_histogram(fill="darkblue",col="white")+
ggtitle("Ultimo Acquisto (Giorni)")+labs(x="Ultimo Acquisto",y="Conteggio")+
geom_point(x=adding_point$LAST_PURCHASE,y=0,col="red",size=4)+
theme(axis.text.x = element_text(angle=45,hjust=1,size=12),
axis.title.x = element_blank(),plot.title = element_text(size=14,face="bold"))
grid.arrange(p1, p2,p3, nrow = 1)
})
# Data being displayed 2 tabitem
output$Data <- DT::renderDataTable({
DT::datatable(summary_2(),rownames = FALSE)%>% formatStyle(
'Outlier',
target = 'row',
color = styleEqual(c(1, 0), c('red', 'black')))%>%formatCurrency(3:3, '')
})
# Check CO_CLIENTE per errori input utente
output$checkcluster <- renderUI({
if (sum(input$cluster%in% user_clustering_raw$CO_CUST)==0)
print ("Errore! Codice Cliente non presente...")})
}
I hope it's clear enough, please don't downgrade

You missed a capital letter:
menuItem("RFM",tabname="RFM",icon = icon("dashboard",lib = "glyphicon")) ## That's the item I ve just added
tabname should be tabName.
Also, tabItem("RFM", should be tabItem("rfm", since it is linked to the id in the tabName parameter.
So, a stripped down working version is given below - minimizing the code is how I found the issue. Hope this helps!
library(shiny)
library(shinydashboard)
library(plotly)
ui <- dashboardPage(
dashboardHeader(title= "Acquisti Clienti CC"),
dashboardSidebar(
sidebarMenu(id="menu",
menuItem(text = "Dashboard", tabName = "dashboard",icon = icon("stats",lib = "glyphicon")),
menuItem(text = "Data", tabName = "Data",icon = icon("th-list",lib = "glyphicon")),
menuItem(text = "RFM", tabName="rfm",icon = icon("th-list",lib = "glyphicon"))
)
),
dashboardBody(
tabItems(
tabItem("dashboard",
p('dashboard')
)
,
tabItem("Data",
p('data')
),
tabItem("rfm",
p('rfm')
)
)
)
)
server <- function(input,output){}
shinyApp(ui,server)

Related

updatePickerInput does not respond to reactive data

I am putting together an Shiny app to allow users to upload an area of interest (AOI), and calculate the amount of overlap with an administrative boundary (WMU). Everything is working as desired, except that my picker input options do not update. The picker input works, but I would like the choices to only include the WMU that overlap the AOI instead of all possible WMU. I can calculate the WMU ID that should populate the list, shown in the "TEST_TEXT"output below the map frame, but cannot successfully update the pickerInput. This kmz will overlap the several WMU that are loaded at the beginning of the script included below:
library(shiny)
library(sf)
library(tidyverse)
library(bcdata)
library(shinyjs)
library(leaflet)
library(mapview)
library(DT)
library(pals)
library(shinyWidgets)
library(shinymanager)
WMU_DATA <-
bcdc_get_data("wildlife-management-units") %>% st_transform(4326) %>% mutate(Total.WMU.HA =
as.numeric(st_area(.)) / 10000)
##### UI #####
ui <- fluidPage(
tags$head(tags$style(
HTML(
".shiny-notification {
height: 100px;
width: 400px;
position:fixed;
top: calc(25% - 50px);;
left: calc(50% - 200px);;
}
"
)
)),
# Application title
titlePanel("Calculate Overlap With WMU"),
# Inputs
sidebarLayout(
sidebarPanel(
width = 3,
textInput(
inputId = "AOI_NAME",
label = "AOI Name",
value = NULL
),
HTML("<br><br>"),
fileInput(
inputId = "KMZ",
label = "Choose KMZ",
multiple = FALSE,
accept = c('.kmz')
),
h3("or"),
HTML("<br><br>"),
fileInput(
inputId = "SHAPEFILE",
label = "Choose shapefile",
multiple = TRUE,
accept = c('.shp', '.dbf', '.sbn', '.sbx', '.shx', '.prj', '.xml')
),
pickerInput(
inputId = "WMU_FILTER",
label = "Filter Overlapping WMU",
choices = unique(WMU_DATA$WILDLIFE_MGMT_UNIT_ID),
selected = unique(WMU_DATA$WILDLIFE_MGMT_UNIT_ID),
multiple = TRUE,
options = list(`actions-box` = TRUE)
),
HTML("<br><br>")
),
# Display OUtputs
mainPanel(
width = 9,
leafletOutput("OVERLAP_MAP", height = 750),
h3(textOutput("TEST_TEXT")),
DTOutput("AOI_OVERLAP_TABLE")
)
)
)
######server#####
server <- function(input, output, session) {
####reactive data
AOI <-
reactive({
if (is.null(input$SHAPEFILE) & !is.null(input$KMZ)) {
st_read(unzip(input$KMZ$datapath)) %>%
st_zm(drop = T) %>%
mutate(AOI_NAME = input$AOI_NAME) %>%
st_transform(4326) %>%
select(-Name)
}
else if (!is.null(input$SHAPEFILE) & is.null(input$KMZ)) {
SHAPEFILE()
}
else{
return(NULL)
}
})
WMU_OVERLAP <- reactive({
st_filter(WMU_DATA, AOI())
})
AOI_WMU_INTERSECT <-
reactive({
st_intersection(AOI(), WMU_OVERLAP()) %>%
mutate(`HA of Overlap` = round(as.numeric(st_area(.)) / 10000, 0)) %>%
mutate(`Percent of WMU` = round(`HA of Overlap` / `Total.WMU.HA` *
100, 2))
})
observeEvent(AOI_WMU_INTERSECT
,
{
updatePickerInput(
session,
"WMU_FILTER",
choices = unique(AOI_WMU_INTERSECT()$WILDLIFE_MGMT_UNIT_ID),
selected = unique(AOI_WMU_INTERSECT()$WILDLIFE_MGMT_UNIT_ID)
)
},
ignoreInit = TRUE,
ignoreNULL = TRUE)
###outputs
output$OVERLAP_MAP <-
renderLeaflet({
withProgress(message = "Calcualting Overlap", detail = "Should be done soon", {
AOI_SPATIAL <- AOI() %>% mutate(AOI_NAME = input$AOI_NAME)
WMU <-
WMU_OVERLAP() %>% filter(WILDLIFE_MGMT_UNIT_ID %in% input$WMU_FILTER)
Overlap <-
AOI_WMU_INTERSECT() %>% filter(WILDLIFE_MGMT_UNIT_ID %in% input$WMU_FILTER)
MAP <-
mapview(
Overlap,
zcol = "WILDLIFE_MGMT_UNIT_ID",
alpha.regions = 0.2,
map.types = c("Esri.WorldTopoMap", "Esri.WorldImagery"),
col.regions = alphabet(nlevels(
as.factor(WMU$WILDLIFE_MGMT_UNIT_ID)
))
) +
mapview(
WMU,
zcol = "WILDLIFE_MGMT_UNIT_ID",
alpha.regions = 0.2,
lwd = 3,
col.regions = alphabet(nlevels(
as.factor(WMU$WILDLIFE_MGMT_UNIT_ID)
)),
hide = TRUE
) +
mapview(AOI_SPATIAL,
label = "AOI_NAME",
col.regions = "red")
MAP#map %>%
setView(st_coordinates(st_centroid(st_as_sfc(
st_bbox(AOI_SPATIAL)
)))[, 1],
st_coordinates(st_centroid(st_as_sfc(
st_bbox(AOI_SPATIAL)
)))[, 2],
zoom = 9)
})
})
output$AOI_OVERLAP_TABLE <-
renderDT({
AOI_OVERLAP_TABLE <- AOI_WMU_INTERSECT() %>%
st_drop_geometry()
AOI_OVERLAP_TABLE
}, filter = "top", extensions = c("FixedHeader", "Buttons"),
options = list(
pageLength = 100,
fixedHeader = TRUE,
dom = "Bfrtip",
buttons = c('colvis', 'copy', 'excel', 'csv')
))
output$TEST_TEXT <-
renderText(unique(AOI_WMU_INTERSECT()$WILDLIFE_MGMT_UNIT_ID))
}
# Run the application
shinyApp(ui = ui, server = server)
Putting some req() and changing observeEvent() to observe() makes it work. Try this
######server#####
server <- function(input, output, session) {
####reactive data
AOI <-
reactive({
if (is.null(input$SHAPEFILE) & !is.null(input$KMZ)) {
st_read(unzip(input$KMZ$datapath)) %>%
st_zm(drop = T) %>%
mutate(AOI_NAME = input$AOI_NAME) %>%
st_transform(4326) %>%
select(-Name)
}
else if (!is.null(input$SHAPEFILE) & is.null(input$KMZ)) {
SHAPEFILE()
}
else{
return(NULL)
}
})
WMU_OVERLAP <- reactive({
req(AOI())
st_filter(WMU_DATA, AOI())
})
AOI_WMU_INTERSECT <-
reactive({
req(AOI(), WMU_OVERLAP())
st_intersection(AOI(), WMU_OVERLAP()) %>%
dplyr::mutate(`HA of Overlap` = round(as.numeric(st_area(.)) / 10000, 0)) %>%
dplyr::mutate(`Percent of WMU` = round(`HA of Overlap` / `Total.WMU.HA` *100, 2))
})
observe({updatePickerInput(
session,
"WMU_FILTER",
choices = unique(AOI_WMU_INTERSECT()$WILDLIFE_MGMT_UNIT_ID),
selected = unique(AOI_WMU_INTERSECT()$WILDLIFE_MGMT_UNIT_ID)
)
} )#, ignoreInit = TRUE, ignoreNULL = TRUE)
###outputs
output$OVERLAP_MAP <-
renderLeaflet({
req(AOI_WMU_INTERSECT())
withProgress(message = "Calcualting Overlap", detail = "Should be done soon", {
AOI_SPATIAL <- AOI() %>% dplyr::mutate(AOI_NAME = input$AOI_NAME)
WMU <-
WMU_OVERLAP() %>% dplyr::filter(WILDLIFE_MGMT_UNIT_ID %in% input$WMU_FILTER)
Overlap <-
AOI_WMU_INTERSECT() %>% dplyr::filter(WILDLIFE_MGMT_UNIT_ID %in% input$WMU_FILTER)
MAP <-
mapview(
Overlap,
zcol = "WILDLIFE_MGMT_UNIT_ID",
alpha.regions = 0.2,
map.types = c("Esri.WorldTopoMap", "Esri.WorldImagery"),
col.regions = alphabet(nlevels(
as.factor(WMU$WILDLIFE_MGMT_UNIT_ID)
))
) +
mapview(
WMU,
zcol = "WILDLIFE_MGMT_UNIT_ID",
alpha.regions = 0.2,
lwd = 3,
col.regions = alphabet(nlevels(
as.factor(WMU$WILDLIFE_MGMT_UNIT_ID)
)),
hide = TRUE
) +
mapview(AOI_SPATIAL,
label = "AOI_NAME",
col.regions = "red")
MAP#map %>%
setView(st_coordinates(st_centroid(st_as_sfc(
st_bbox(AOI_SPATIAL)
)))[, 1],
st_coordinates(st_centroid(st_as_sfc(
st_bbox(AOI_SPATIAL)
)))[, 2],
zoom = 9)
})
})
output$AOI_OVERLAP_TABLE <-
renderDT({
AOI_OVERLAP_TABLE <- AOI_WMU_INTERSECT() %>% st_drop_geometry()
AOI_OVERLAP_TABLE
}, filter = "top", extensions = c("FixedHeader", "Buttons"),
options = list(
pageLength = 100,
fixedHeader = TRUE,
dom = "Bfrtip",
buttons = c('colvis', 'copy', 'excel', 'csv')
))
output$TEST_TEXT <- renderText(unique(AOI_WMU_INTERSECT()$WILDLIFE_MGMT_UNIT_ID))
}

Is there a way of getting renderValueBox() to be compatible with Shiny Theme?

I'm currently developing a dashboard that displays value boxes that are either green or red depending if they're positive/negative. This functions perfectly without using shiny themes but as soon as I use it I lose the color in the value box and it just uses the primary colour of the theme. Any help would be really appreciated.
library(shiny)
library(shinydashboard)
library(RPostgreSQL)
library(DT)
library(RPostgres)
library(dplyr)
library(highcharter)
library(formattable)
library(ggplot2)
library(shinythemes)
data = read.csv('nazare_dash_data2.csv')
colnames(data)[which(names(data) == "X")] <- "Date"
data$Date = as.Date(data$Date,tryFormats = c("%Y-%m-%d", "%Y/%m/%d"))
ui = fluidPage(theme = shinytheme("cyborg"),
dashboardHeader(title = 'Nazare Point Ltd.'),
dashboardSidebar(disable = TRUE),
dashboardBody(
#------------------------ DAILY BOX -------------------------------------------
box(title = 'Daily', width = 12, collapsible = TRUE,
tabBox(width = 12,height = 12,
tabPanel('Data',
column(width = 3,
selectInput(inputId = 'Date',label = 'Date',choices = unique(data$Date),multiple = FALSE)
),
column(width = 3,
valueBoxOutput('Realised_Options',width = 12),
valueBoxOutput('Realised_Futures',width = 12)
),
column(width = 3,
valueBoxOutput('Unrealised_Options',width = 12),
valueBoxOutput('Unrealised_Futures',width = 12),
valueBoxOutput('Fees',width = 12)
),
column(width = 3,
valueBoxOutput('Options_Total',width = 12),
valueBoxOutput('Futures_Total',width = 12),
valueBoxOutput('PNL',width = 12)
)
),
tabPanel('Plots')
)
) ,
#-----------------------BOX YEAR TO DATE ---------------------------------------
box(width = 12, title = 'Year To Date', collapsible = TRUE,
column(width = 4,
valueBoxOutput('YTD_PNL',width =12),
valueBoxOutput('YTD_Fees',width =12)
),
column(width = 8,
plotOutput('ytd_pnl',width = "100%")
)
),
#----------------------- DATATABLE BOX------------------------------------------
box(width = 12,collapsible = TRUE,
DT::dataTableOutput(outputId = "table")
)
) # </dashboardBody>
) # </dashboardPage>
server = function(input,output){thematic::thematic_shiny()
filtered_data = reactive({
data = filter(data, Date == input$Date)
return(data)
})
color_pnl = function(x){
if(x > 0){
color = 'green'
}
else{
color = 'red'
}
return(color)
}
# ----------------------- DAILY OUTPUTS ----------------------------------------
output$Realised_Options = renderValueBox({
valueBox(paste(prettyNum(filtered_data()[,c('OptRlzd')],big.mark=",",scientific=FALSE)),
'Options Realised',
color = color_pnl(filtered_data()[,c('OptRlzd')]))
})
output$Realised_Futures = renderValueBox({
valueBox(paste(prettyNum(filtered_data()[,c('FutRlzd')],big.mark=",",scientific=FALSE)),
'Futures Realised',
color = color_pnl(filtered_data()[,c('FutRlzd')]))
})
output$Unrealised_Options = renderValueBox({
valueBox(paste(prettyNum(filtered_data()[,c("OptionsEDFOpenEq")],big.mark=",",scientific=FALSE)),
'Options Unrealised',
color = color_pnl(filtered_data()[,c("OptionsEDFOpenEq")]))
})
output$Unrealised_Futures = renderValueBox({
valueBox(paste(prettyNum(filtered_data()[,c("EDFCalcOpenEq")],big.mark=",",scientific=FALSE)),
'Futures Unrealised',
color = color_pnl(filtered_data()[,c("EDFCalcOpenEq")]))
})
output$Options_Total = renderValueBox({
valueBox(paste(prettyNum((filtered_data()[,c("OptionsEDFOpenEq")] + filtered_data()[,c('OptRlzd')]),big.mark=",",scientific=FALSE)),
'Total Options',
color = color_pnl(filtered_data()[,c("OptionsEDFOpenEq")]))
})
output$Futures_Total = renderValueBox({
valueBox(paste(prettyNum((filtered_data()[,c("EDFCalcOpenEq")] + filtered_data()[,c('FutRlzd')]),big.mark=",",scientific=FALSE)),
'Total Futures',
color = color_pnl(filtered_data()[,c("OptionsEDFOpenEq")]))
})
output$PNL = renderValueBox({
valueBox(paste(prettyNum(filtered_data()[,c('PL')],big.mark=",",scientific=FALSE)),
'Total PNL (Net Fees)',
color = color_pnl(filtered_data()[,c('PL')]))
})
output$Fees = renderValueBox({
valueBox(paste(filtered_data()[,c('Fees')]),'Fees')
})
#------------------------YEAR TO DATE OUTPUTS-----------------------------------
output$YTD_PNL = renderValueBox({
valueBox(paste(prettyNum(sum(data$PL),big.mark=",",scientific=FALSE)),
'PNL',
color = color_pnl(sum(data[,c('PL')])))
})
output$YTD_Fees = renderValueBox({
valueBox(paste(prettyNum(sum(data$Fees),big.mark=",",scientific=FALSE)),
'Fees',
color = 'red')
})
output$ytd_pnl = renderPlot({
ggplot(data=data, aes(Date,cumsum(PL))) + geom_line(colour = "#009E73") + geom_point()
})
# ------------------------------------------------------------------------------
output$table = DT::renderDataTable(DT::datatable(style = "bootstrap",{
data
}))
}
shinyApp(ui,server)

Read Reactive Elements from Shiny Module

I'm trying to use some reactive elements from predefined function and call that data from a module to generate plots, but data is not getting updated upon selection. I've also tried to call the function inside reactive() and call that from the module, but still same result. My approach is below:
library(shiny)
library(shinyWidgets)
library(highcharter)
library(data.table)
library(dplyr)
employement_type_count <- function(
data,
category,
...
){
data[employee_category %in% category, .(count = .N), by = employee_category]
}
pie_chart_ui <- function(id) {
ns <- NS(id)
highchartOutput(ns("pie"))
}
pie_chart_server <- function(
id,
data,
var_x = names(data)[1],
var_y = names(data)[2],
lab_x = names(data)[1],
lab_y = names(data)[2],
tooltip_name = names(data)[2],
export_title = NA
) {
moduleServer(
id,
function(input, output, session) {
output$pie <- renderHighchart({
data %>%
hchart(
'pie',
hcaes_(x = var_x, y = var_y),
name = tooltip_name
) %>%
hc_xAxis(title = list(text = lab_x)) %>%
hc_yAxis(title = list(text = lab_y)) %>%
hc_plotOptions(
pie = list(
allowPointSelect = TRUE,
cursor = 'pointer',
dataLabels = list(
enabled = TRUE,
format = '<b>{point.name}</b>: {point.percentage:.1f}%',
style = list(
color = "(Highcharts.theme && Highcharts.theme.contrastTextColor) || 'black'"
)
)
)
) %>%
hc_exporting(
enabled = TRUE,
buttons = list(
contextButton = list(
align = 'right'
)
),
chartOptions = list(
title = list(
text = export_title
)
)
)
})
}
)
}
ui <- fluidPage(
sidebarPanel(
pickerInput(
"employee_type",
"Employee Type",
choices = c("Regular", "Project", "Service", "Part-Time"),
selected = c("Regular", "Project", "Service", "Part-Time"),
multiple = TRUE
)
),
mainPanel(
pie_chart_ui("employee_category")
)
)
server <- function(input, output, session){
# data_common <- fread("data_common.csv")
data_common <- data.table(
id = 1:26,
employee_name = LETTERS,
gender_type = rep(c("Male", "Female"), each = 13),
employee_category = c("Regular", "Project", rep(c("Regular", "Project", "Service", "Part-Time"), times = 6))
)
pie_chart_server(
"employee_category",
employement_type_count(
data_common,
input$employee_type
)
)
}
shinyApp(ui, server)
Note that, data should be imported from server, instead of global, as it is constantly getting updated.
One way to do it is shown below.
library(shiny)
library(shinyWidgets)
library(highcharter)
library(data.table)
library(dplyr)
df1 <- data.table(
id = 1:26,
employee_name = LETTERS,
gender_type = rep(c("Male", "Female"), each = 13),
employee_category = c("Regular", "Project", rep(c("Regular", "Project", "Service", "Part-Time"), times = 6))
)
employement_type_count <- function(
data,
category,
...
){
data <- data()
if (is.null(category())) {df <- data
}else df <- data[employee_category %in% category(), .(count = .N), by = employee_category]
return(df)
}
pie_chart_ui <- function(id) {
ns <- NS(id)
highchartOutput(ns("pie"))
}
pie_chart_server <- function(
id,
data,
var_x = names(data)[1],
var_y = names(data)[2],
lab_x = names(data)[1],
lab_y = names(data)[2],
tooltip_name = names(data)[2],
export_title = NA
) {
moduleServer(
id,
function(input, output, session) {
output$pie <- renderHighchart({
data %>%
hchart(
'pie',
hcaes_(x = var_x, y = var_y),
name = tooltip_name
) %>%
hc_xAxis(title = list(text = lab_x)) %>%
hc_yAxis(title = list(text = lab_y)) %>%
hc_plotOptions(
pie = list(
allowPointSelect = TRUE,
cursor = 'pointer',
dataLabels = list(
enabled = TRUE,
format = '<b>{point.name}</b>: {point.percentage:.1f}%',
style = list(
color = "(Highcharts.theme && Highcharts.theme.contrastTextColor) || 'black'"
)
)
)
) %>%
hc_exporting(
enabled = TRUE,
buttons = list(
contextButton = list(
align = 'right'
)
),
chartOptions = list(
title = list(
text = export_title
)
)
)
})
}
)
}
ui <- fluidPage(
sidebarPanel(
pickerInput(
"employee_type",
"Employee Type",
choices = c("Regular", "Project", "Service", "Part-Time"),
selected = c("Regular", "Project", "Service", "Part-Time"),
multiple = TRUE
)
),
mainPanel(
pie_chart_ui("employee_category")
)
)
server <- function(input, output, session){
# data_common <- fread("data_common.csv")
data_common <- reactive(df1)
employee <- reactive(input$employee_type)
observe({
mydata <- employement_type_count(
data_common,
employee
)
pie_chart_server(
"employee_category",
mydata
)
})
}
shinyApp(ui, server)

Selecting many items from the list in R

I created an application in Shiny where I would like to choose multiple items from the drop-down menu. Unfortunately, I don't know how to make items on the list reduce after a given menu selection. By which all lines merge into a whole. what should I add in the code so that each model is a separate line. Below I put a picture with charts.
My code:
library(shiny)
library(plotly)
library(readxl)
library(shinyWidgets)
library(shinydashboard)
library(shinyjs)
library(DT)
df1 <- data.frame(Month = rep(month.abb[1:12],10,replace = TRUE), Model = paste0('Ferrari ', rep(LETTERS[1:10], each = 12)),
Value = sample(c(0:300),120, replace = T),
Car = rep('Ferrari', 10,each = 12), Year = rep(2019:2020, each = 60),Country = rep(c("USA","DE"), each = 12, times = 5), stringsAsFactors = F)
df2 <- data.frame(Month = rep(month.abb[1:12],10,replace = TRUE), Model = paste0('Porsche ', rep(LETTERS[1:10], each = 12)),
Value = sample(c(0:300),120, replace = T),
Car = rep('Porsche', 10,each = 12), Year = rep(2019:2020, each = 60), Country = rep(c("USA","DE"), each = 12, times = 5),stringsAsFactors = F)
data <-rbind(df1, df2)
ui <- fluidPage(
titlePanel("Test"),
sidebarLayout(
sidebarPanel( width = 3,
uiOutput("category1"),
uiOutput("category2"),
uiOutput("category3"),
uiOutput("category4")),
mainPanel(
tabsetPanel(type = "tabs",
tabPanel("Plot", plotlyOutput("plot", height = 550,width = 1000))
)
)
)
)
server <- function(input, output,session) {
output$category1 <- renderUI({
selectInput('cat1', 'Choose year:', multiple = T, selected = NULL, choices = sort(as.numeric(unique(data$Year))))
})
df_subset <- eventReactive(input$cat1,{
if(input$cat1=="All") {df_subset <- data}
else{df_subset <- data[data$Year == input$cat1,]}
})
df_subset1 <- reactive({
if(is.null(input$cat2)){df_subset()} else {df_subset()[df_subset()$Country %in% input$cat2,]}
})
output$category2 <- renderUI({
selectInput('cat2', 'Choose country:', choices = sort(as.character(unique(df_subset()$Country))), multiple = T, selected = NULL)
})
df_subset2 <- reactive({
if(is.null(input$cat3)){df_subset1()} else {df_subset1()[df_subset1()$Car %in% input$cat3,]}
})
output$category3 <- renderUI({
selectInput('cat3', 'Choose car:', choices = sort(as.character(unique(df_subset1()$Car))), multiple = F, selected = NULL)
})
df_subset3 <- reactive({
if(is.null(input$cat4)){df_subset2()} else {df_subset2()[df_subset2()$Model %in% input$cat4,]}
})
output$category4 <- renderUI({
pickerInput('cat4', 'Choose model:', choices = sort(as.character(unique(df_subset2()$Model))), multiple = TRUE, selected = NULL)
})
output$plot <- renderPlotly({
xform <- list(categoryorder = "array",
categoryarray = df_subset3()$Month,
title = " ",
nticks=12)
plot_ly(data=df_subset3(), x=~Month, y = ~Value, type = 'scatter', mode = 'lines', name = 'Value') %>%
layout(title = " ",xaxis = xform) %>%
layout(legend = list(orientation = 'h', xanchor = "center", y=1.1, x=0.5))
})
}
shinyApp(ui, server)
To display each model as a separate line on the plot, you can assign the Model column of your dataset to the color parameter of plot_ly this way:
plot_ly( data = df_subset3(), x = ~Month, y = ~Value, color = ~Model, ...)

the outputs don't update in my shiny app

I have problems in my shiny app. all the inputs show the correct response from the server but, when i select the choice 5 in the checkboxgroup the app return the correct thing. but after, when i try other inputs only show the update of box (dyplot1) and the anothers boxes(dyplot2 and prediction) keep static. this is a sample code:
# funciones ----
addDays <- function(data,date,days) {
for(i in 1:days){
data[length(data)+1] <- NA
date[length(date)+1] <- date[length(date)]+1
}
y <- xts(data,order.by = date)
return(y)
}
addDaysForecast <- function(forecast,date,days) {
data <- rep(NA,length(date))
for(i in 1:days){
data[length(data)+1] <- forecast[i]
date[length(date)+1] <- date[length(date)]+1
}
y <- xts(data,order.by = date)
return(y)
}
plotForecast <- function(table,forecast) {
days <-length(forecast)
date <-as.Date(table[,"ENTRYTIME"])
values <- as.numeric(table[,"CLOSINGPRICE"])
series <- addDays(values,date,days)
serieForecast <- addDaysForecast(forecast,date,days)
day1 <- date[length(date)-days*2]
day2 <- date[length(date)]+7
curvas <- cbind(series,serieForecast)
graf <- dygraph(curvas, main = table[1,1]) %>%
dySeries("..1", label = "datos", color = "black") %>%
dySeries("..2", label = " Forecast", stepPlot = TRUE, color = "green") %>%
dyAxis("y", label = "CLOSINGPRICE") %>%
dyCrosshair(direction = "vertical") %>%
dyRangeSelector(dateWindow = c(day1, day2)) %>%
##dyOptions(maxNumberWidth = 20, stackedGraph = FALSE) %>%
dyLegend(width = 400) %>%
dyHighlight(highlightCircleSize = 3,
highlightSeriesBackgroundAlpha = 0.2,
hideOnMouseOut = FALSE) %>%
dyRangeSelector()
return(graf)
}
plotNormal <- function(table,thing) {
date <-as.Date(table[,"ENTRYTIME"])
values <- as.numeric(table[,thing])
series <- xts(values, order.by = date)
ma1 <- xts(runMean(values, n = 6),order.by = date)
ma2 <- xts(runMean(values, n = 12),order.by = date)
ma3 <- xts(runMean(values, n = 20),order.by = date)
mv1 <- xts(runVar(values, n = 6), order.by = date)
mv2 <- xts(runVar(values, n = 12), order.by = date)
mv3 <- xts(runVar(values, n = 20), order.by = date)
ske1 <- xts(movskew(values,6), order.by = date)
ske2 <- xts(movskew(values,12), order.by = date)
ske3 <- xts(movskew(values,20), order.by = date)
curvas <- cbind(series,ma1,ma2,ma3,mv1,mv2,mv3,ske1,ske2,ske3)
graf <- dygraph(curvas, main = table[1,1], group = "ALL") %>%
dySeries("..1", label = "datos", color = "black") %>%
dySeries("..2", label = "Ma6", color = "red") %>%
dySeries("..3", label = "Ma12", color = "blue") %>%
dySeries("..4", label = "Ma20", color = "green") %>%
dySeries("..5", label = "Mv6",strokePattern = "dashed",axis = 'y2', color = "red") %>%
dySeries("..6", label = "Mv12",strokePattern = "dashed",axis = 'y2', color = "blue") %>%
dySeries("..7", label = "Mv20",strokePattern = "dashed",axis = 'y2',color = "green") %>%
dySeries("..8", label = " as 6", stepPlot = TRUE, color = "red") %>%
dySeries("..9", label = " as 12", stepPlot = TRUE, color = "blue") %>%
dySeries("..10", label = " as 20", stepPlot = TRUE, color = "green") %>%
dyAxis("y", label = thing) %>%
dyCrosshair(direction = "vertical") %>%
##dyOptions(maxNumberWidth = 20, stackedGraph = FALSE) %>%
dyLegend(width = 400) %>%
dyHighlight(highlightCircleSize = 3,
highlightSeriesBackgroundAlpha = 0.2,
hideOnMouseOut = FALSE) %>%
dyRangeSelector()
return(graf)
}
status <- function(table,forecast) {
test <- table[nrow(table)-1:nrow(table),]
last <- test[,"CLOSINGPRICE"]
if(length(forecast)==1|| forecast==-1 ){
return(("No se a realizado predicción para este nemo"))
}else if (last<forecast[1]){
return(paste("A la alza con precio de cierre: ",forecast[1]))
}else if(last>forecast[1]){
return(paste("A la baja con precio de cierre: ",forecast[1]))
}
}
##skewness moving
movskew <- function(values,n) {
values2 <- values
for(i in 1:n){
values2[i] <- NA
}
num <- n
for(i in 1:(length(values)-n)){
num <- num + 1
values2[num] <- as.numeric(skewness(values[i:num]))
}
return(values2)
}
whatshow <- function(array) {
showthis <- vector()
for(i in 1:5){
showthis[i] <- any(array==i)
}
return(showthis)
}
getforecast <- function(path) {
url <- paste0("http://192.168.1.9:3169/api/forecast/", path, "?format=json")
response <- jsonlite::fromJSON(url)
if(length(response)>1){
return(response$forecast)
}else{
return(-1)
}
}
whatPlot <- function(table,name,show,thing) {
if(show[5]==TRUE){
fore <- getforecast(name)
plotForecast(table,fore)
}else{
plotNormal(table,thing) %>%
dyVisibility(visibility=c(show[1],
rep(show[2],3),
rep(show[3],3),
rep(show[4],3)))
}
}
dyVisibility <- function (dygraph, visibility = TRUE){
dygraph$x$attrs$visibility <- visibility
dygraph
}
#creando la tabla de prueba
table <- data.frame(matrix(1, nrow = 100, ncol = 18))
nombres <- c("SYMBOL" ,
"BOOKING_REF_ID",
"BIDQTY",
"BIDPRICE",
"OFFERQTY",
"OFFERPRICE",
"TRADEQTY",
"TRADEPRICE",
"OPENINGPRICE",
"CLOSINGPRICE",
"HIGHPRICE",
"LOWPRICE",
"VWAPPRICE",
"IMBALANCE",
"VOLUME",
"AMOUNT",
"TREND",
"ENTRYTIME")
colnames(table) <- nombres
table$ENTRYTIME <-seq.POSIXt(as.POSIXct("2015-01-01", tz="GMT"),
as.POSIXct("2015-4-10", tz="GMT"), by="1 day")
# estructura pagina ----
header <- dashboardHeader(title = "Basic dashboard")
sidebar <- dashboardSidebar( collapsed = TRUE,
sidebarMenu(
menuItem("Dashboard", tabName = "dashboard", icon = icon("dashboard")),
menuItem("Widgets", tabName = "widgets", icon = icon("th"))
)
)
body <- dashboardBody(
tabItems(
# First tab content
tabItem(tabName = "dashboard",
fluidRow(
column(width = 9,
box(title = "Grafico 1", status = "primary", width = NULL,
solidHeader = TRUE, collapsible = TRUE,
dygraphOutput("dyPlot1",height = "300px")),
box(title = "Grafico 2", status = "primary", width = NULL,
solidHeader = TRUE, collapsible = TRUE,
dygraphOutput("dyPlot2",height = "300px"))
),
column(width = 3,
box(title = "Inputs", status = "warning", solidHeader = TRUE, width = NULL,
selectInput("var1",
label = "1) variable",
choices = nombres[3:16],
selected = "CLOSINGPRICE"),
selectInput("var2",
label = "2) variable",
choices = nombres[3:16],
selected = "VOLUME"),
checkboxGroupInput("checkGroup", label = h3("Ver:"),
choices = list("Datos" = 1, "Medias" = 2,
"Esperanzas" = 3,"Asimetrias"=4, "Forecast"=5),
selected = 1),
box(title = "Predicción",status = "warning", solidHeader = TRUE, width = NULL,
verbatimTextOutput("prediction"))
)
)
)
),
# Second tab content
tabItem(tabName = "widgets",
h2("Widgets tab content")
)
)
)
# app ----
app <- shinyApp(
#UI
ui <- dashboardPage(header,sidebar,body),
server <- function(input, output) {
observeEvent(input$checkGroup, {
#... # do some work
output$prediction <- renderText({
forecast <- getforecast("CAMANCHACA")
status(table,forecast)
})
#... # do some more work
})
output$dyPlot1 <- renderDygraph({
show <- whatshow(input$checkGroup)
whatPlot(table,"CAMANCHACA",show,input$var1)
})
output$dyPlot2 <- renderDygraph({
show <- whatshow(input$checkGroup)
whatPlot(table,"CAMANCHACA",show,input$var2)
})
}
)
# Run the app ----
runApp(app,host="0.0.0.0",port=3838)

Resources