I recently started using Shiny and I need help with shiny dashboard errors. I am trying to build an app using Shiny Dashboard, But I keep getting errors: "Error in tagAssert(sidebar, type = "aside", class = "main-sidebar") :
object 'sidebar' not found"
Can Someone help me fix the error??
Thanks in Advance
library(shiny)
library(shinydashboard)
library(DT)
library(tidyverse)
library(plotly)
covid <- read.csv("covid.csv")
covid_deaths <- read.csv("COVID_DEATHS_UK.csv")
noncovid_deaths <- read.csv("NON_COVID_DEATHS_UK.csv")
title <- tags$a(href='https://ourworldindata.org/covid-vaccinations?country=OWID_WRL',
'COVID 19 Vaccinations')
function(request){
sidebar <- dashboardSidebar(
hr(),
sidebarMenu(id="tabs",
menuItem("Global COVID data",
menuSubItem("COVID vaccinations: Deaths Vs All variable", tabName = "Dashboard"),
selectInput("location", "1. Select a country",
choices = covid$location, selectize = TRUE, multiple = FALSE),
menuSubItem("Scatterplot", tabName = "Scatterplot", icon = icon("line-chart")),
menuSubItem("Regression", tabName = "Regression", icon = icon("cog")),
menuSubItem("Multicollinearity", tabName = "Multicollinearity", icon = icon("line-chart")),
menuSubItem("Summary", tabName = "Summary", icon = icon("file-o-text")),
menuSubItem("DataTable", tabName = "DataTable", icon = icon("table"), selected=TRUE)
),
menuItem("COVID_Deaths", tabName = "COVID Deaths", icon = icon("line-chart")),
menuItem("NonCOVID_Deaths", tabName = "Non COVID Deaths", icon = icon("line-chart"))
)
)
body <- dashboardBody(
tabItems(
tabItem(tabName = "Scatterplot",
fluidRow(
column(width = 6,
tabPanel("Scatterplot", plotlyOutput("scatterplot"),
verbatimTextOutput("correlation")),
tabPanel(helpText("Select variables for scatterplot"),
selectInput(inputId = "y", label = "Y-axis:",
choices = c("total_deaths", "new_deaths"),
selected = "Deaths"),
br(),
selectInput(inputId = "x", label = "X-axis:",
choices = names(subset(covid,select = -c(total_deaths,new_deaths,
iso_code, continent,date,location), na.rm =TRUE)),
selectize = TRUE,
selected = "Comparator variables")
))))),
tabItems(
tabItem(tabName = "Regression",
fluidRow(
column(width = 6,
tabPanel(verbatimTextOutput(outputId = "regsum"),
verbatimTextOutput(outputId = "indprint"),
verbatimTextOutput(outputId = "depprint")),
tabPanel(helpText("Select input for Independent variables"),
selectInput(inputId = "indvar", label = "Independent Variable", multiple = TRUE,
choices = list("total_cases", "total_vaccinations", "people_fully_vaccinated", "total_boosters","stringency_index",
"population_density", "aged_65_older","gdp_per_capita","extreme_poverty", "cardiovasc_death_rate", "diabetes_prevalence", "handwashing_facilities", "life_expectancy","human_development_index")),
helpText("Select input for dependent variables"),
selectInput(inputId = "depvar", label = "Dependent variable", multiple = FALSE,
choices = list("total_deaths","new_deaths","new_cases")))
)))),
tabItems(
tabItem(tabName = "Multicollinearity",
fluidRow(
tabPanel(img(src="Multicollinearity.png"))))),
tabItems(
tabItem(tabName = "Summary",
fluidRow(tabPanel(
verbatimTextOutput("summary")
)))),
tabItems(
tabItem(tabName = "DataTable",
fluidRow(tabPanel(DTOutput("dataset")),
tabPanel(helpText("Select the Download Format"),
radioButtons("type", "4. Format type:",
choices = c("Excel (csv)", "Text(tsv)", "Doc")),
br(),
helpText("Click on the download button to download dataset"),
downloadButton("downloadData", "Download"))))),
tabItems(tabItem(tabName = "COVID Deaths",
fluidRow(tabPanel(plotlyOutput("hist1")),
tabPanel(helpText("Select Variables for a COVID deaths"),
selectInput(inputId = "Yaxis", label = "yaxis:",
choices = names(subset(covid_deaths, select = -c(Week_number,Week_ending)))))))),
tabItems(tabItem(tabName = "NonCOVID Deaths",
fluidRow(tabPanel(plotlyOutput("hist2")),
tabPanel(helpText("Select Variables for a NOn- COVID deaths"),
selectInput(inputId = "ya", label = "Yaxis:",
choices = names(subset(noncovid_deaths, select = -c(Week_number,Week_ending))))))))
)
}
ui <- dashboardPage(skin = "black",
dashboardHeader(title = title),
sidebar,body)
server <- function(input, output, session) {
output$location <- renderPrint({
locationfilter <- subset(covid, covid$location == input$location)
})
output$summary <- renderPrint({
summary(covid)
})
datasetinput <- reactive({covid})
fileExt <- reactive({
switch(input$type,
"Excel (csv)" = "csv", "Text (tsv)" = "tsv", "Doc" = "doc")
})
output$dataset <- renderDT(
covid, options = list(
pageLength = 50,
initComplete = JS('function(setting, json) { alert("done"); }')
)
)
output$downloadData <- downloadHandler(
filename = function(){
paste("covid", fileExt(),sep = ".")
},
content = function(file){
sep <- switch(input$type,
"Excel (csv)" = ",", "Text (tsv)" = "\t", "Doc" = " ")
write.table(datasetinput(), file, sep = sep, row.names = FALSE)
}
)
output$scatterplot <- renderPlotly({
#ggplot(subset(covid, covid$location == input$location),aes(y= input$y,x=input$x))+geom_point()
ggplotly(ggplot(subset(covid, covid$location == input$location),
aes(y = .data[[input$y]], x = .data[[input$x]],col = factor(stringency_index)))+
geom_smooth()+geom_point()+labs(col ="Stringency Index"))
})
output$correlation <- renderText({
x <- covid[covid$location == input$location, input$x]
y <- covid[covid$location == input$location, input$y]
xy = data.frame(x,y)
xy = xy[complete.cases(xy),]
var(xy)
cor(xy,method = 'pearson')
})
output$hist1 <- renderPlotly({
ggplotly(ggplot(covid_deaths, aes(x=Week_number, y= .data[[input$Yaxis]]))+
geom_point()
)
})
output$hist2 <- renderPlotly({
ggplotly(ggplot(noncovid_deaths, aes(x=Week_number, y= .data[[input$ya]]))+
geom_point()
)
})
lm1 <- reactive({lm(reformulate(input$indvar, input$depvar), data = subset(covid, covid$location == input$location))})
output$depPrint <- renderPrint({input$depvar})
output$indPrint <- renderPrint({input$indvar})
output$regsum <- renderPrint({summary(lm1())})
}
# Shiny dashboard
shiny::shinyApp(ui, server)
Related
I am trying to create a shinyApp with a a set of tabsetPanels within tabsetPanels. However, if on one of those embedded tabsetPanels I have a tabPanel that has a reactive value (a radioButton or a checkboxInput, for example), the reactive item doesn't work, and its value in input is NULL. This is causing some of my graphs to not render properly, if they are in a box with a selector. Any idea of why this is happening or what I can do to fix it would be great.
A reprex app (in this case, the checkBoxInput for the y axis is working, but on my actual app it is not.)
library(shiny)
library(shinythemes)
library(shinydashboard)
library(shinyjs)
library(tidyverse)
options(warn=-1)
data(iris)
data(mtcars)
# Define UI for application that draws a histogram
ui <- dashboardPage(
dashboardHeader(),
dashboardSidebar(
shinyjs::useShinyjs(),
sidebarMenu(id = "menume",
#selectInput("which unit", "Choose a unit", choices = c("aa", "bb", "cc", "dd")),
selectInput("colorme", "Choose a color", c("red", "yellow", "green", "blue", "black")),
#sidebarMenuOutput("colormenu"),
menuItem("MTCARS", tabName = "mt", icon = icon("user-tie")),
selectInput("mtvar", "Choose a variable", choices = colnames(mtcars)),
menuItem("IRIS", icon = icon("envelope-open-text"), tabName = "ir"),
selectInput("irvar", "Choose a variable", choices = colnames(iris))
)
),
dashboardBody(
tabItems(
tabItem("mt", uiOutput("mttabs")),
tabItem("ir", uiOutput("irtabs"))
)
)
)
# ui <- secure_app(ui, enable_admin = TRUE)
# Begin Server ----------------------------------------------
server <- function(input, output, session) {
# output$colormenu = renderMenu({
# # Remove the req
# selectInput("colorme", "Choose a color", c("red", "yellow", "green", "blue", "black"))
#
#
# })
permission_color = reactive({
if(input$colorme =="green"){
TRUE
}else{
FALSE
}
})
output$mttabs = renderUI({
output$mtcarsplot1=renderPlot({
myplot = ggplot(mtcars, aes_string(x = input$mtvar)) + stat_bin(nbins = 10)
if(input$tenfoldmt == TRUE){myplot = myplot+ylim(c(0,10))}
myplot
})
output$mtcarsplot2=renderPlot({
ggplot(mtcars, aes_string(x = input$mtvar)) + geom_density()
})
output$mtcarstable1=renderTable({
tabme= head(mtcars, 5)
tabme
})
if(permission_color()==TRUE){
tabsetPanel(id = "mtcarstabsall",
tabPanel("Plots",
tabsetPanel(id = "mtplotsall",
tabPanel(id = "mtplots","mtcars plots",value=2,
fluidRow(box(title = "Plot1",
checkboxInput("tenfoldmt", "Y axis lim 10?", value = FALSE),
plotOutput("mtcarsplot1"))
)),
tabPanel(id = "mtplots2","mtcars plots 2",value=3,
fluidRow(box(title = "Plot2", plotOutput("mtcarsplot2")))))
),
tabPanel("Tables",
tabsetPanel(id = "mttables",
tabPanel(id = "mttable","MTcars tables",value=1,
fluidRow(box(title = "Table 1", tableOutput("mtcarstable1")))
)))
)
} else{
tabsetPanel(id = "mtcarstabsall",
tabPanel("Plots",
tabsetPanel(id = "mtplotsall",
tabPanel(id = "mtplots","mtcars plots",value=2,
fluidRow(box(title = "Plot1",
checkboxInput("tenfoldmt", "Y axis lim 10?", value = FALSE),
plotOutput("mtcarsplot1"))
)),
tabPanel(id = "mtplots2","mtcars plots 2",value=3,
fluidRow(box(title = "Plot2", plotOutput("mtcarsplot2")))))
)
)
}
})
output$irtabs = renderUI({
output$irisplot1=renderPlot({
myplot = ggplot(iris, aes_string(x = input$irvar)) + stat_bin(nbins = 10)
if(input$tenfoldir == TRUE){myplot = myplot+ylim(c(0,10))}
myplot
})
output$irisplot2=renderPlot({
ggplot(iris, aes_string(x = input$irvar)) + geom_density()
})
output$iristable1=renderTable({
tabme = head(iris, 5)
tabme
})
if(permission_color()==TRUE){
tabsetPanel(id = "iristabsall",
tabPanel("Plots",
tabsetPanel(id = "irisplotsall",
tabPanel(id = "irisplots","iris plots",value=5,
fluidRow(box(title = "Plot1",
checkboxInput("tenfoldir", "Y axis lim 10?", value = FALSE),
plotOutput("irisplot1"))
)),
tabPanel(id = "irisplots2","iris plots 2",value=6,
fluidRow(box(title = "Plot2", plotOutput("irisplot2"))
)))
),
tabPanel("Tables",
tabsetPanel(id = "iristables",
tabPanel(id = "irtable","iris tables",value=4,
fluidRow(box(title = "Table 1", tableOutput("iristable1")))
)))
)
} else{
tabsetPanel(id = "iristabsall",
tabPanel("Plots",
tabsetPanel(id = "irisplotsall",
tabPanel(id = "irisplots","iris plots",value=5,
fluidRow(box(title = "Plot1",
checkboxInput("tenfoldir", "Y axis lim 10?", value = FALSE),
plotOutput("irisplot1"))
)),
tabPanel(id = "irisplots2","iris plots 2",value=6,
fluidRow(box(title = "Plot2", plotOutput("irisplot2"))
)))
))
}
})
}
shinyApp(ui, server)
I have a modularized Golem app using bs4Dash. I want to update the active sidebar tab from an actionBttn that is dynamically generated from renderUI. While updatebs4ControlbarMenu works as expected as shown here, it does not work in the modularized version of the application. What am I doing wrong? I suspect it is related to input[[btnID]] management across modules but I struggle to find the solution.
Working example without modules as shown here:
library(shiny)
library(shinyWidgets)
library(bs4Dash)
library(tidyverse)
shinyApp(
ui = bs4DashPage(
sidebar_collapsed = FALSE,
controlbar_collapsed = TRUE,
enable_preloader = FALSE,
navbar = bs4DashNavbar(skin = "dark"),
sidebar = bs4DashSidebar(
inputId = "sidebarState",
bs4SidebarMenu(
id = "sidebr",
bs4SidebarMenuItem(
"Tab 1",
tabName = "tab1"
),
bs4SidebarMenuItem(
"Tab 2",
tabName = "tab2"
)
)
),
bs4DashBody(
bs4TabItems(
bs4TabItem(
tabName = "tab1",
h1("Welcome!"),
fluidRow(
pickerInput(
inputId = "car",
label = "Car",
choices = row.names(mtcars),
selected = head(row.names(mtcars), 3),
multiple = TRUE,
options = list(
`actions-box` = TRUE)
),
pickerInput(
inputId = "gear",
label = "Gear",
choices = unique(mtcars$gear),
selected = unique(mtcars$gear),
multiple = TRUE,
options = list(
`actions-box` = TRUE)
)
),
fluidRow(
column(6,
uiOutput("uiboxes")
)
)
),
bs4TabItem(
tabName = "tab2",
h4("Yuhuuu! You've been directed automatically in Tab 2!")
)
)
)
),
server = function(input, output, session) {
submtcars <- reactive({
req(input$car, input$gear)
mtcars %>%
mutate(
carnames = rownames(mtcars)) %>%
filter(
carnames %in% input$car &
gear %in% input$gear
)
})
observeEvent( submtcars(), {
n_ex <- nrow(submtcars())
output$uiboxes <- renderUI({
lapply(1:n_ex, FUN = function(j) {
print(paste("j is ", j))
bs4Box(
title = submtcars()$carnames[j],
width = 12,
str_c("Number of gears:", submtcars()$gear[j]),
btnID <- paste0("btnID", j),
print(btnID),
fluidRow(
column(
2,
actionBttn(
inputId = btnID,
icon("search-plus")
)
)
)
)
})
})
lapply(1:n_ex, function(j) {
btnID <- paste0("btnID", j)
observeEvent(input[[btnID]] , {
updatebs4ControlbarMenu(
session,
inputId = "sidebr",
selected = "tab2"
)
})
})
})
}
)
Modularized attempt not working:
library(shiny)
library(shinyWidgets)
library(bs4Dash)
library(tidyverse)
mod_exlib_ui <- function(id){
ns <- NS(id)
tagList(
fluidRow(
pickerInput(
inputId = ns("car"),
label = "Car",
choices = row.names(mtcars),
selected = head(row.names(mtcars), 3),
multiple = TRUE,
options = list(
`actions-box` = TRUE)
),
pickerInput(
inputId = ns("gear"),
label = "Gear",
choices = unique(mtcars$gear),
selected = unique(mtcars$gear),
multiple = TRUE,
options = list(
`actions-box` = TRUE)
)
),
fluidRow(
column(6,
uiOutput(ns("uiboxes"))
)
)
)
}
mod_exlib_server <- function(id){
moduleServer( id, function(input, output, session){
ns <- session$ns
submtcars <- reactive({
# req(input$car, input$gear)
mtcars %>%
dplyr::mutate(
carnames = rownames(mtcars)) %>%
dplyr::filter(
carnames %in% input$car &
gear %in% input$gear
)
})
observeEvent( submtcars(), {
n_ex <- nrow(submtcars())
output$uiboxes <- renderUI({
lapply(1:n_ex, FUN = function(j) {
print(paste("j is ", j))
bs4Box(
title = submtcars()$carnames[j],
width = 12,
paste("Number of gears: ", submtcars()$gear[j]),
btnID <- paste0("btnID", j),
print(btnID),
fluidRow(
column(
2,
actionBttn(
inputId = ns(btnID),
icon("search-plus")
)
)
)
)
})
})
lapply(1:n_ex, function(j) {
btnID <- paste0("btnID", j)
observeEvent(input[[btnID]] , {
print(btnID)
updatebs4ControlbarMenu(
session,
inputId = "sidebr",
selected = "exdet2"
)
})
})
})
})
}
app_ui <- tagList(
bs4DashPage(
navbar = bs4DashNavbar(),
sidebar = bs4DashSidebar(
expand_on_hover = TRUE,
inputId = "sidebarState",
bs4SidebarMenu(
id = "sidebr",
bs4SidebarMenuItem(
"Tab 1",
tabName = "tab1"
),
bs4SidebarMenuItem(
"Tab 2",
tabName = "tab2"
)
)
),
bs4DashBody(
bs4TabItems(
bs4TabItem(
tabName = "tab1",
h1("Welcome!"),
mod_exlib_ui("exlib_ui_1")
),
bs4TabItem(
tabName = "tab2",
h4("Yuhuuu! You've been directed automatically in Tab 2!")
)
)
)
)
)
app_server <- function( input, output, session ) {
# Your application server logic
mod_exlib_server("exlib_ui_1")
}
shinyApp(
ui = app_ui,
server = app_server)
After exploring the example of function updatebs4TabSetPanel() that is in the same family, it seems that the selected value needs to be a number.
Hence, you can use this code with CRAN version 0.5.0:
updatebs4ControlbarMenu(
session,
inputId = "sidebr",
selected = "2" #"exdet2"
)
I'm trying to render t.test and ANOVA results reactively.
I found that length(unique(x)) or n_distinct(x) does not work in shiny server section.
Here are my codes.
ui <- dashboardPage(
dashboardHeader(
title = "testpage"
),
dashboardSidebar(
sidebarMenu(
menuItem("data", tabName = "data", icon = icon("file-csv")),
menuItem("descrptive", tabName = "widget1", icon = icon("chart-bar"))
)
),
dashboardBody(
tabItems(
tabItem(tabName = "data",
fluidRow(
box(width = 6, height=200, title ="file",
fileInput("file0","select a file", buttonLabel = "select", accept = c(".csv")),
DTOutput('dt')),
)),
tabItem(tabName = "widget1",
fluidRow(
box(width = 4, title = "Variances",
selectInput(
"sel","methods", c("prop","mean")
),
selectizeInput(
'a', 'group', choices = colnames(file),
options = list(
placeholder = 'Please select a variable below',
onInitialize = I('function() { this.setValue(""); }')
)),
conditionalPanel(
condition = "input.sel == 'mean' ",
selectizeInput(
'b', 'vector', choices = colnames(file), multiple =T,
options = list(
placeholder = 'Please select a variable below',
onInitialize = I('function() { this.setValue(""); }')
)
)
),
box(
width = 8, title = "results",
dataTableOutput("tbl1"),
dataTableOutput("tbl2")
),
),
fluidRow(
box(title = "p.value",
actionButton("go","tests"),
uiOutput("results")
),
)
)
)
)
)
server <- function(input, output, session) {
data <- reactive({
data.table::fread(input$file0$datapath)
})
output$dt <- DT::renderDT({
req(input$file0)
data()
})
observeEvent(input$file0, {
mytable <- read.csv(input$file0$datapath) %>% as_tibble()
req(mytable)
updateSelectInput(session, "a", label = "group", choices = colnames(mytable))
updateSelectInput(session, "b", label = "vector", choices = colnames(mytable))
updateSelectInput(session, "x", label = "X Variable", choices = colnames(mytable))
updateSelectInput(session, "y", label = "Y Variable", choices = colnames(mytable))
updateSelectInput(session, "z", label = "Z Variable", choices = colnames(mytable))
})
# prop -----------------------------
proptable <- reactive({
data() %>%
filter(!is.na(input$a)) %>%
group_by_(input$a) %>% summarise(n = n()) %>% mutate(percentage = round(n/sum(n)*100,1))
})
output$tbl1 <- renderDataTable(extensions = "Buttons",
options = list(dom = "Bfrtip",
buttons = "copy"),{
validate(
need(input$a !="", message = "select variables.")
)
if(input$sel == "prop")
proptable()
})
# mean ------------------------------------------
meantable <- reactive({
data() %>% filter(!is.na(input$a)) %>%
group_by_at(input$a) %>%
summarise_at(vars(input$b), funs(round(mean(., na.rm = T), digits = 2)))
})
output$tbl2 <- renderDataTable(extensions = "Buttons",
options = list(dom = "Bfrtip",
buttons = "copy"),{
if(input$sel == "mean")
meantable()
})
myeval=function(text){
eval(parse(text=text))
}
# tests --------------------------
output$results<- renderUI({
input$go
isolate({
for(i in seq_along(input$b)){
local({
j<-i
rstname <- paste0("result",j)
output[[rstname]]=renderPrint({
if(length(unique(input$a, na.rm = T))>2)
{
formul = paste0(input$b[j],"~",input$a)
fm = myeval(formul)
anova(lm(fm, data= data()))
}
else if(length(unique(input$a, na.rm=T))>2){
x <- t.test(fm2, data= data())
x$p.value}
})
})
}
rstlist <- lapply(1:length(input$b),function(i){
rstname <- paste0("result",i)
verbatimTextOutput(rstname)
})
do.call(tagList, rstlist)
})
})
I tried to figure out the problem, using observeEvent, realized that length(unique(x)) or n_distinct(x) keeps showing the results like so.
observeEvent(input$go,{
cat("n_distinct of", input$a, "is", length(unique((data[,"input$a"]), na.rm=T)), ".\n")
})
n_distinct of ee_a is ee_a . ##results
Would you mind if help me fix this problem?
Thank you!
I would like to be able to display a multi-line graph with an imported csv. CSV files contain time series. On import, I would like to be able to choose, knowing that the name of the fields can change according to the CSV, the field representing the X and the one of Y, and define the field containing the ID which will create the various lines. Something like this :
For now, I have this but it's completly wrong
# ui.R
library(shiny)
library(shinydashboard)
library(ggplot2)
shinyUI(
dashboardPage(
dashboardHeader(title ="Sen2extract"),
sidebar <- dashboardSidebar(
sidebarMenu(
menuItem("Chart", tabName = "chart")
)
),
dashboardBody(
tabItem(tabName = "chart",
box(
width = 12, collapsible=FALSE,
fileInput(inputId = "csv_chart", label = "Upload your CSV", multiple = FALSE,
accept = c(".csv", "text/csv", "text/comma-separated-values,text/plan"), width = "300px"),
selectInput("X", label = "Field X :", choices = list("Choice 1" = "")),
selectInput("Y", label = "Field Y :", choices = list("Choice 1" = "")),
selectInput("group", label = "Group by :", choices = list("Choice 1" = ""))
),
box(plotOutput("plot"), width = 12)
)
)
)
)
# server.R
library(shiny)
library(shinydashboard)
library(ggplot2)
shinyServer(function(input, output, session){
output$plot = renderPlot({
data <- read.csv(file = input$csv_chart)
ggplot(data) +
geom_line(mapping = aes(x = input$X, y = input$Y)) +
labs (x = "Years", y = "", title = "Index Values")
})
})
there were several issues with your code and I have a working version below.
The main issue was that you have to read your data within reactive() and then update the selection. Also, to have multiple lines in your graph, you have to add what to group on in ggplot when you define the mapping in aes or in this case aes_string. I chose color as this gives multiple lines colored according to different groups in the chosen column.
library(shiny)
library(shinydashboard)
library(tidyverse)
ui <- dashboardPage(
dashboardHeader(title ="Sen2extract"),
sidebar <- dashboardSidebar(
sidebarMenu(
menuItem("Chart", tabName = "chart")
)
),
dashboardBody(
tabItem(tabName = "chart",
box(
width = 12, collapsible=FALSE,
fileInput(inputId = "csv_chart", label = "Upload your CSV",
multiple = FALSE,
accept = c(".csv",
"text/csv",
"text/comma-separated-values,text/plan"),
width = "300px"),
selectInput("X", label = "Field X:", choices = "Pending Upload"),
selectInput("Y", label = "Field Y:", choices = "Pending Upload"),
selectInput("group", label = "Group by:", choices = "Pending Upload")
),
box(plotOutput("plot"), width = 12)
)
)
)
server <- function(input, output, session){
data <- reactive({
req(input$csv_chart)
infile <- input$csv_chart
if (is.null(infile))
return(NULL)
df <- read_csv(infile$datapath)
updateSelectInput(session, inputId = 'X', label = 'Field X:',
choices = names(df), selected = names(df)[1])
updateSelectInput(session, inputId = 'Y', label = 'Field Y:',
choices = names(df), selected = names(df)[2])
updateSelectInput(session, inputId = 'group', label = 'Group by:',
choices = names(df), selected = names(df)[3])
return(df)
})
output$plot <- renderPlot({
ggplot(data()) +
geom_line(mapping = aes_string(x = input$X, y = input$Y, color=input$group)) +
labs(x = "Years", y = "", title = "Index Values")
})
}
shinyApp(ui = ui, server = server)
The process_map() function in the server in the R shiny script creates the diagram image as below. My requirement is that there are two attributes "FUN" and "units" that are part of the performance() function. They have standard four values each that are available in the ui code below under PickerInput ID's Case4 and Case5. Currently, I am hard coding the value to create the map, can you help me to use the id's in the server code and make it dynamic such that when I select the value in the PickerInput, the formula fetches the value directly. Thanks and please help.
library(shiny)
library(shinydashboard)
library(bupaR)
library(processmapR)
library(lubridate)
library(dplyr)
library(edeaR)
library(shinyWidgets)
library(DiagrammeR)
ui <- dashboardPage(
dashboardHeader(title = "Diagram Plot",titleWidth = 290),
dashboardSidebar(width = 0),
dashboardBody(
tabsetPanel(type = "tab",
tabPanel("Overview", value = 1,
box(
column(1,
dropdown(
pickerInput(inputId = "resources",
label = "",
choices = c("Throughput Time"),
choicesOpt = list(icon = c("fa fa-bars",
"fa fa-bars",
"fa fa-safari")),
options = list(`icon-base` = "")),
circle = FALSE, status = "primary", icon = icon("list", lib = "glyphicon"), width = "300px"
),
conditionalPanel(
condition = "input.resources == 'Throughput Time' ",
tags$br(),
tags$br(),
tags$br(),
dropdown(
pickerInput(inputId = "Case4",
label = "Select the Process Time Summary Unit",
choices = c("min","max","mean","median"), options = list(`actions-box` = TRUE),
multiple = F),
circle = FALSE, status = "primary", icon = icon("eye-close", lib = "glyphicon"), width = "300px"
),
tags$br(),
tags$br(),
tags$br(),
dropdown(
pickerInput(inputId = "Case5",
label = "Select the Process Time Unit",
choices = c("mins","hours","days","weeks"), options = list(`actions-box` = TRUE),
multiple = F, selected = "days"),
circle = FALSE, status = "primary", icon = icon("eye-close", lib = "glyphicon"), width = "300px"
))),
title = "Process Map",
status = "primary",height = "575", width = "500",
solidHeader = T,
column(10,grVizOutput("State")),
align = "left")
),
id= "tabselected"
)))
server <- function(input, output) {
output$State <- renderDiagrammeR(
{
if(input$resources == "Throughput Time")
patients %>% process_map(performance(FUN = mean,units = "days"))
else
return()
})}
shinyApp(ui, server)
test this:
output$State <- renderDiagrammeR({
if(input$resources == "Throughput Time")
{
if(input$Case4=="mean"){
patients %>% process_map(performance(FUN = mean,units = input$Case5))}
else if(input$case4=="min"){
patients %>% process_map(performance(FUN = min,units = input$Case5))
}else if(input$case4=="max"){
patients %>% process_map(performance(FUN = max ,units = input$Case5))
}else{
patients %>% process_map(performance(FUN = median ,units = input$Case5))
}
}else
return()
})
or you can use this:
patients %>%
process_map(performance(FUN = eval(parse(text=input$Case4)) ,units = input$Case5))
enjoy;)
here is a sample:
library(shiny)
ui <- fluidPage(
selectInput(inputId = "func", label = "Choose The Function", choices = c("mean", "sum", "median"))
,
textOutput("text")
)
server <- function(input, output, session) {
main_data <- reactive({
data.frame(a= rnorm(100), b=rnorm(100) )
})
output$text <- renderText({
df <- main_data()
apply(df,2, FUN = eval(parse(text=input$func)) )
})
}
shinyApp(ui = ui, server = server)
You could use do.call to call a function from its name, see the example below. You can add arguments by adding them in the list in the do.call function, e.g. list(x,units=input$Case5).
library(shiny)
x=c(1,2,3,4,5,6,7)
ui <- fluidPage(
selectInput('select','Select Function: ', choices=c('mean','max','min','median')),
textOutput('text')
)
server <- function(input,output)
{
output$text <- renderText({
result = do.call(input$select, list(x))
paste0('The ', input$select, ' of [', paste(x,collapse=', '),'] is ', result)
})
}
shinyApp(ui,server)
Hope this helps!