I have the following code to dynamically make either Check Boxes or Sliders.
server <- shinyServer(function(input, output, session) {
# define the data frame to use
dat <- mtcars
dat <- rownames_to_column(dat, "car")
# name of availale data frame
varNames <- names(dat)
# define defaul values as the first value in each column
defaultValues <- as.numeric(dat[1,])
# store the selected variable in a reactive variable
# dynamically creates a set of sliders
output$controls <- renderUI({
div(
fluidRow(
column(9, uiOutput("rangeUI"))
)
)
})
output$rangeUI <- renderUI({
lapply(1:length(varNames), function(k) {
fluidRow(
column(12,
if (is_character(dat[1, k])) {
# a slider range will created only is the variable is selected
checkboxGroupInput(paste0("slider_", varNames[k]), label = varNames[k], choices = unique(dat[[k]]), selected = NULL,
inline = FALSE, width = NULL, choiceNames = NULL, choiceValues = NULL)
} else {
# otherwise uses single value with a default value
sliderInput(paste0("slider_", varNames[k]), label = varNames[k],
min = 0, max = 100, value = defaultValues[k])
}
)
)
})
})
The issue I am running into is that I would like to display the sliders and check boxes side by side until they hit the screen width and then start a new row. Currently, they are all in one column.
Is there a good way to dynamically adjust offset to accomplish this, maybe something like this?
column(12, offset = match(k, colnames(dat)), # then lead into the if else statement
Any other suggestions on building the UI are welcome.
Try to put the fluidRow outside the lapply and change the size of the column from 12 to maybe 3, otherwise you are creating multiple rows with only one column, instead on one row with multiple columns.
Below is your code modified, maybe it could help you.
library(shiny)
library(tibble)
ui <- fluidPage(
uiOutput("controls")
)
server <- shinyServer(function(input, output, session) {
# define the data frame to use
dat <- mtcars
dat <- rownames_to_column(dat, "car")
# name of availale data frame
varNames <- names(dat)
# define defaul values as the first value in each column
defaultValues <- as.numeric(dat[1,])
# store the selected variable in a reactive variable
# dynamically creates a set of sliders
output$controls <- renderUI({
fluidRow(
column(offset = 3, 9, uiOutput("rangeUI"))
)
})
# to test that a dynamically created input works with an observer
observeEvent(input$slider_mpg, {
cat("slider_mpg:", input$slider_mpg, "\n")
})
output$rangeUI <- renderUI({
fluidRow(
lapply(1:length(varNames), function(k) {
column(3,
if (is.character(dat[1, k])) {
# a slider range will created only is the variable is selected
checkboxGroupInput(paste0("slider_", varNames[k]), label = varNames[k], choices = unique(dat[[k]]), selected = NULL,
inline = FALSE, width = NULL, choiceNames = NULL, choiceValues = NULL)
} else {
# otherwise uses single value with a default value
sliderInput(paste0("slider_", varNames[k]), label = varNames[k],
min = 0, max = 100, value = defaultValues[k])
}
)
})
)
})
})
shinyApp(ui = ui, server = server)
Update:
You can get the values of dynamically created inputs by using an action button as is explained here or get them automatically by using the solution explained here.
Related
I need a reactive variable (declared server-side) available after start-up. Using what I learned here How to create a conditional renderUI in Shiny dashboard I tried wrapping in reactive() before defining the UI but no luck. Moving topValuesSelector to the UI inside a conditionalPanel would work except conditional panels apparently do not like the %in% operator (a separate issue that I also tried to resolve w/o success).
if (interactive()) {
library(shiny)
library(shinydashboard)
library(shinydashboardPlus)
ui <-
dashboardPage(header = dashboardHeaderPlus(left_menu = tagList(
dropdownBlock(
id = "prefDropdown",
title = "Preferences",
icon = NULL,
badgeStatus = NULL,
checkboxGroupInput(
inputId = "prefDropdown",
label = NULL,
choices = c("Pareto",
"Legend on chart",
"Cases/1K uniques",
"Top 10 only"),
selected = c("Pareto", "Cases/1K uniques", "Top 10 only")
),
uiOutput("topValues")
)
)),
dashboardSidebar(),
dashboardBody(fluidRow(box(
title = "Top",
textOutput("topN")
))))
server <- function(input, output) {
topValuesSelector <- reactive({
if ("Top 10 only" %in% input$prefDropdown) {
numericInput(
inputId = "topValues",
label = NULL,
width = "25%",
value = 10,
min = 1,
max = 30,
step = 1
)
}
})
output$topValues <- renderUI({
topValuesSelector()
})
observe({
if ("Top 10 only" %in% input$prefDropdown) {
output$topN <- renderText(input$topValues)
} else{
output$topN <- renderText(100)
}
})
}
shinyApp(ui, server)
}
The intent is for the initial value of "topValues" to be 10 with this value immediately available. However, no value is available which causes an error. Using req() avoids the error by pausing execution but that is not a viable approach because "topValues" is needed for a plot. So no plot until selecting "prefDropdown".
It looks like the problem is that input$topValues does not exist until you click on the Preferences button. Since the UI element isn't needed it hasn't been created yet.
In order to work around that you can create a variable that detects whether or not the input is available and if not use a default value.
if (interactive()) {
library(shiny)
library(shinydashboard)
library(shinydashboardPlus)
ui <-
dashboardPage(header = dashboardHeaderPlus(left_menu = tagList(
dropdownBlock(
id = "prefDropdown",
title = "Preferences",
icon = NULL,
badgeStatus = NULL,
checkboxGroupInput(
inputId = "prefDropdown",
label = NULL,
choices = c("Pareto",
"Legend on chart",
"Cases/1K uniques",
"Top 10 only"),
selected = c("Pareto", "Cases/1K uniques", "Top 10 only")
),
uiOutput("topValues")
)
)),
dashboardSidebar(),
dashboardBody(fluidRow(box(
title = "Top",
textOutput("topN")
))))
server <- function(input, output) {
## We want to use the same default value in two places so create a var
default_value <- 10
topValuesSelector <- reactive({
if ("Top 10 only" %in% input$prefDropdown) {
numericInput(
inputId = "topValues",
label = NULL,
width = "25%",
value = default_value, ## Change to use the default value
min = 1,
max = 30,
step = 1
)
}
})
output$topValues <- renderUI({
topValuesSelector()
})
## Create a variable that is the default value unless the input is available
myTopN <- reactive({
if(length(input$topValues)>0){
return(input$topValues)
}
return(default_value)
})
observe({
if ("Top 10 only" %in% input$prefDropdown) {
# output$topN <- renderText(input$topValues)
output$topN <- renderText(myTopN()) ## Use our new variable instead of the input directly
} else{
output$topN <- renderText(100)
}
})
}
shinyApp(ui, server)
}
There are a couple of other things going on with your code. Notice that "Top 10 only" %in% input$prefDropdown will not do what you think it is doing. You have to check to see if "Top 10 only" is TRUE... I'll leave you there to start another question if you get stuck again.
This one has me really going around in circles.
I am working on an R script that loads a dataframe and uses fields from the dataframe to populate a hierarchical set of selectizeInput. E.g. each of the inputs represent a subset of what is in the previous. Each SubRegion contains multiple LCC’s, Each LCC contains multiple ENB’s, and so on.
When the user select a value in any of the inputs, that value will used to filter the dataframe and all of the other selectizeInputs need to be updated from the filtered data.
It seems to work fine for the first input (SubRegionInput) but every time I try to get it to respond to and/or filter by any of the others (e.g. add input$LCCInput to the observe block) they get populated for a few seconds and then go blank.
I suspect the answer is quite simple and/or I am doing something really dumb, but I am a total hack with no formal R training so am probably missing something quite basic (if so sorry).
Below is a partial chunk of code (sorry I can’t include it all but this is for work and I can’t share the details of what I am doing).
NOTES
The current outputs are just so I can see what is going on while I develop this portion of the code.
I know right now it is only set up to filter on the one value…everything I have tried to do it on more has failed so I included the most functional code I have so far.
ui <- fluidPage(
# Application title
titlePanel("KPI DrillDown"),
# Sidebar with a slider input for number of bins
fluidRow(
selectizeInput("SubRegionInput", "SubRegion", SubRegionList ,selected = NULL, multiple = TRUE),
selectizeInput("LCCInput", "LCC", LCCList,selected = NULL, multiple = TRUE),
selectizeInput("ENBIDInput", "ENBID", ENBIDList,selected = NULL, multiple = TRUE),
selectizeInput("SiteNumInput", "SiteNumber", SiteNumberList,selected = NULL, multiple = TRUE),
selectizeInput("SiteNameInput", "SiteName", SiteNameList,selected = NULL, multiple = TRUE),
selectizeInput("LNCELInput", "LNCell", LNCellList,selected = NULL, multiple = TRUE),
selectizeInput("SectorInput", "Sector", SectorList,selected = NULL, multiple = TRUE),
mainPanel(
#plotOutput("distPlot")
verbatimTextOutput("SubRegionText"),
verbatimTextOutput("LCCText"),
verbatimTextOutput("view")
)
)
)
server <- function(input, output) {
observe({
input$SubRegionInput
temp <- SiteInfo[SiteInfo$SITE_SUB_REGION %in% input$SubRegionInput, ]
thisLCCList = sort(temp$BACKHAUL_LCC[!is.na(temp$BACKHAUL_LCC)])
updateSelectizeInput(session = getDefaultReactiveDomain()
, inputId = "LCCInput"
, choices = thisLCCList
, selected= NULL)
thisENBIDList = sort(temp$ENODEB_ID[!is.na(temp$ENODEB_ID)])
updateSelectizeInput(session = getDefaultReactiveDomain()
, inputId = "ENBIDInput"
, choices = thisENBIDList
, selected= NULL)
thisSiteNumberList = sort(temp$SITE_NUMBER[!is.na(temp$SITE_NUMBER)])
updateSelectizeInput(session = getDefaultReactiveDomain()
, inputId = "SiteNumInput"
, choices = thisSiteNumberList
, selected= NULL)
thisSiteNameList = sort(temp$SITE_NAME[!is.na(temp$SITE_NAME)])
updateSelectizeInput(session = getDefaultReactiveDomain()
, inputId = "SiteNameInput"
, choices = thisSiteNameList
, selected= NULL)
thisLNCellList = sort(temp$SECTOR_NUMBER[!is.na(temp$SECTOR_NUMBER)])
updateSelectizeInput(session = getDefaultReactiveDomain()
, inputId = "LNCELInput"
, choices = thisLNCellList
, selected= NULL)
thisSectorList = sort(temp$Sector[!is.na(temp$Sector)])
updateSelectizeInput(session = getDefaultReactiveDomain()
, inputId = "SectorInput"
, choices = thisSectorList
, selected= NULL)
output$view<- renderPrint(temp)
})
Since I do not have access to your data, I used mtcars as an example.
To begin with, since you have so many filtering, I would suggest creating a search or update button, which is what I did in my codes. I only did one filtering using dplyr after extracting all the selectizeInputs. I have to manually change all the empty searching parameter to select all in order to avoid filtering to NA.
Overall, I think the problem with your code was you are observing too many updateSelectizeInputs at once. I did try to recreate using your way, and what I ended with was that I could only update single selectizeInput, and the other selectizeInputs were not selectable.
Hopefully, this method fits your data.
Codes:
library(shiny)
library(dplyr)
library(DT)
data <- mtcars
SubRegionList <- unique(data$cyl)
LCCList <- unique(data$gear)
ENBIDList <- unique(data$am)
SiteNumberList <- unique(data$vs)
# Define UI
ui <- fluidPage(
# Application title
titlePanel("KPI DrillDown"),
# Sidebar with a slider input for number of bins
fluidRow(
selectizeInput("SubRegionInput", "SubRegion/cyl", SubRegionList ,selected = NULL, multiple = TRUE),
uiOutput("LCCInput"),
uiOutput("ENBIDInput"),
uiOutput("SiteNumInput"),
uiOutput("Search"),
mainPanel(
verbatimTextOutput("view")
)
)
)
# Define server logic required
server <- function(input, output, session) {
SiteInfo <- data
# temp <- ""
observe({
if (!is.null(input$SubRegionInput)){
subRegionSelected <- input$SubRegionInput
## Create a temp dataset with the selected sub regions.
temp <- SiteInfo[SiteInfo$cyl %in% subRegionSelected, ]
## Push the newly created selectizeInput to UI
output$LCCInput <- renderUI({
selectizeInput("LCCInput", "LCC/gear", unique(temp$gear), selected = NULL, multiple = TRUE)
})
output$ENBIDInput <- renderUI({
selectizeInput("ENBIDInput", "ENBID/am", unique(temp$am),selected = NULL, multiple = TRUE)
})
output$SiteNumInput <- renderUI({
selectizeInput("SiteNumInput", "SiteNumber/vs", unique(temp$vs), selected = NULL, multiple = TRUE)
})
output$Search <- renderUI({
actionButton("Search", "Search")
})
## Function that linked to the actionButton
display <- eventReactive(input$Search,{
temp <- SiteInfo[SiteInfo$cyl %in% input$SubRegionInput, ]
# ## manually change all the empty searching parameter to select all in order to avoid filtering to NA
LCC <- input$LCCInput
if (is.null(input$LCCInput)){LCC <- unique(temp$gear)}
ENBID <- input$ENBIDInput
if (is.null(input$ENBIDInput)){EBVID <- unique(temp$am)}
SiteNum <- input$SiteNumInput
if (is.null(input$SiteNumInput)){LCC <- unique(temp$vs)}
## Dplyr::filter data
temp <- temp %>%
filter(gear %in% LCC & am %in% ENBID & vs %in% SiteNum)
temp
})
## Run the actionButton
output$view <- renderPrint({
display()
})
} else {
## Display waht the data looks like when no Sub Region is selected
output$view<- renderPrint(data)
}
})
}
# Run the application
shinyApp(ui = ui, server = server)
To edit a one-to-many like data structure,
I would like to create a data table (DTOutput), on which I observe cell clicks observeEvent(input$groupingsOut_cell_clicked, {...}).
Then at every cell click, I would like to generate input fields on the UI.
Finally, I would like to listen to changed on those rendered/generated UI.
I can't edit these cells directly in the DTOutput, as it doesn't support vectors within cells. (Hence, one-to-many relationship).
I have managed steps 1 and 2. I can render a DTOutput with corresponding cells. I can observe cell clicks and insert UI (insertUI()) upon cell clicks. I created observeEvent objects to observe those rendered fields. However, those observeEvents are never fired upon editing newly generated fields.
ui = fluidPage(title = titlePanel("Title"),
tags$head(tags$style(HTML("hr {border-top: 1px solid #000000;}"))),
sidebarLayout(
sidebarPanel(),
mainPanel(tabsetPanel(type = "tabs",
tabPanel("Groupings", DTOutput(outputId = "groupingsOut"),
tags$div(id = 'placeholder')),
tabPanel("Test", textOutput(outputId = "statusOut")),
tabPanel("Plot Generator", plotOutput(outputId = "distPlotOut")))
)
)
)
server = function(input, output) {
# Label reactive values
labelRVs = list()
#Example table
groupings = data.frame(names = c("cars", "mbikes", "bikes"),
labels = c("Cars", "Motor Bikes", "Bikes"),
groups = I(list(c("toyota", "vw", "tesla"), c("harley", "kawasaki"), c("somth", "anoth", "bla"))),
groupLabels = I(list(c("Toyota", "VW", "Tesla"), c("Harley Davidson", "Kawasaki"), c("Something", "Another Thing", "Bla bla"))))
#groupings = data.frame()
proxy = dataTableProxy('groupingsOut')
observeEvent(input$groupingsOut_cell_clicked, {
info = input$groupingsOut_cell_clicked
if(!is.null(info$row)){
grouping = groupings[[info$row, 1]]
groupingLabel = groupings[[info$row, 2]]
groups = groupings[[info$row, 3]]
groupLabels = groupings[[info$row, 4]]
# remove previously generated UI
removeUI(selector = paste0('#placeholder input'), multiple = TRUE)
removeUI(selector = paste0('#placeholder label'), multiple = TRUE)
# Generating ID for grouping labels
id = paste0("groupLabel_", i)
# Inserting text input for grouping label
insertUI(selector = '#placeholder', ui = textInput(id, label = "Grouping label:", value = groupingLabel))
labelRVs[[id]] <<- observeEvent(id, {
cat(paste(id, i, "\n")) # THIS LINE ONLY RUNS AT INITIALIZATION :(
})
lapply(1:length(groups), function(i){
index = sprintf("%03d", i)
id = paste0('label_', index)
insertUI(selector = '#placeholder',
ui = textInput(id, label = paste0("Group label for ", groups[i], ":"), value = groupLabels[i]))
labelRVs[[id]] <<- observeEvent(id, {
cat(paste(id, i, "\n")) # ALSO THIS LINE ONLY RUNS AT INITIALIZATION :(
})
})
}
})
output$groupingsOut = renderDT(groupings[, c(1, 3)], rownames = FALSE, editable = TRUE, selection = 'single')
}
shinyApp(ui = ui, server = server)
However, this example Shiny - Can dynamically generated buttons act as trigger for an event runs perfectly fine. In the example instead of insertUI into tags, renderUI to outputUI is used. I adapted my code above to use renderUI, which also failed. At this point, I am suspecting if DTOutput doesn't behave the same way as other input fields.
Beaware of the usage of <<- operator to assign labelRVs to keep observeEvent objects alive. This is indeed necessary, which is shown in the example.
I wonder, if there is any way to observe such fields?
I have a shiny app where I want the user to be able to select which variables to keep in the final data frame and then also select which variables to scale into a percent. I have this working, but I am running into a little puzzle. The problem is if the user decides they want to add an additional variable (or remove one), they have to redo the scaling. This could be a problem if my users have many columns they are working on. How can I keep the scaling work the user has already done, while allowing for the addition or removal of variables from the final data frame?
library(shiny)
library(tidyverse)
library(DT)
# Define UI
ui <- fluidPage(
checkboxGroupInput("select_var", label = "Select Variables"),
selectInput("scalescore", label = NULL, choices = c("")),
actionButton("scale", "Scale Scores"),
DT::dataTableOutput("table")
)
# Define server
server <- function(session, input, output) {
# define the reactive values
values <- reactiveValues(df_final = NULL)
# dynamically generate the variable names
observe({
vchoices <- names(mtcars)
updateCheckboxGroupInput(session, "select_var", choices = vchoices)
})
# dynamically generate the variables to scale
observe({
vchoices <- names(values$df_final)
updateSelectInput(session, "scalescore", choices = vchoices)
})
# select the variables based on checkbox
observe({
req(input$select_var)
df_sel <- mtcars %>% select(input$select_var)
values$df_final <- df_sel
})
observeEvent(input$scale, {
name <- rlang::sym(paste0(input$scalescore, "_scaled"))
values$df_final <- values$df_final %>% mutate(!!name := round(!!rlang::sym(input$scalescore)/max(!!rlang::sym(input$scalescore), na.rm = TRUE)*100, 1))})
output$table <- DT::renderDataTable(values$df_final)
}
# Run the application
shinyApp(ui = ui, server = server)
We will need to maintain a vector which tracks whether a variable was scaled or not. Here is how it's done,
library(shiny)
library(tidyverse)
library(DT)
# Define UI
ui <- fluidPage(
checkboxGroupInput("select_var", label = "Select Variables"),
selectInput("scalescore", label = NULL, choices = c("")),
actionButton("scale", "Scale Scores"),
DT::dataTableOutput("table")
)
server = function(input,output,session){
#Column names are static
names = colnames(mtcars)
# data scructure to store if the variable is scaled
is_scaled = logical(length(names))
names(is_scaled) = names #Set the names of the logical vector to the column names
#Update the checkbox with the column names of the dataframe
observe({
updateCheckboxGroupInput(session, "select_var", choices = names)
})
# Update the list of choices but dont include the scaled vaiables
observe({
vchoices <- names(data())
vchoices = vchoices[vchoices %in% names]
updateSelectInput(session, "scalescore", choices = vchoices)
})
#When the scle button is pressed, the vector which contains the list of scaled variables is updated
observeEvent(input$scale,{
if(is_scaled[[input$scalescore]]){
is_scaled[[input$scalescore]] <<- FALSE
}else{
is_scaled[[input$scalescore]] <<- TRUE
}
})
#Function to scale the variables
scale = function(x){
return(round(x/max(x,na.rm = T)*100,1))
}
data = reactive({
req(input$select_var)
input$scale #simply to induce reactivity
#Select the respective columns
df = mtcars%>%
select(input$select_var)
if(any(is_scaled[input$select_var])){
temp_vec = is_scaled[input$select_var] #Get a list of variables selected
true_vec = temp_vec[which(temp_vec)] #Check which ones are scaled
true_vec_names = names(true_vec) #Get the names of the variables scales
#Scale the variables respectively
df = df%>%
mutate_at(.vars = true_vec_names,.funs = funs(scaled = scale(.)))
}
return(df)
})
output$table = DT::renderDataTable(data())
}
# Run the application
shinyApp(ui = ui, server = server)
is_scaled tracks whether a particular column is scaled or not. When it is later selected, it is scaled if the value is TRUE in this vector.
Additional functionality is also added where if the scale button is pressed twice the scale column is removed.
I'm trying to add a dynamic ggvis plot to a Shiny app. First, user picks a dimension, and then adds items from that dimension.
For global.R and sample data, see https://gist.github.com/tts/a41c8581b9d77f131b31
server.R:
shinyServer(function(input, output, session) {
# Render a selectize drop-down selection box
output$items <- renderUI({
selectizeInput(
inputId = 'items',
label = 'Select max 4. Click to delete',
multiple = TRUE,
choices = aalto_all[ ,names(aalto_all) %in% input$dim],
options = list(maxItems = 4, placeholder = 'Start typing')
)
})
selected <- reactive({
if (is.null(input$items)) {
return(aalto_all)
}
df <- aalto_all[aalto_all[[input$dim]] %in% input$items, ]
df$keys <-seq(1, nrow(df))
df
})
selected %>%
ggvis(~WoS, ~NrOfAuthors, fill = ~School, key := ~keys) %>%
layer_points() %>%
add_tooltip(show_title) %>%
bind_shiny("gv")
show_title <- function(x=NULL) {
if(is.null(x)) return(NULL)
key <- x["keys"][[1]]
selected()$Title20[key]
}
})
ui.R:
shinyUI(fluidPage(
titlePanel('Some (alt)metric data for articles published since 2010'),
sidebarLayout(
sidebarPanel(
selectInput(
inputId = "dim",
label = "Dimension",
choices = dimensions,
selected = c("Title")),
uiOutput("items")
),
mainPanel(
tabsetPanel(
# I'll add more tabs
tabPanel("Plot with ggvis", ggvisOutput("gv"))
)
)
)
))
This is OK
in the beginning, when there are no items selected, and all data is plotted. This is a hack because the ggvis object throws an error if there is no data served.
when all selected items are deleted (which is the same as 1.) and another dimension is chosen
But when I try to switch to another dimension without deleting the items first, I get this:
Error in `$<-.data.frame`(`*tmp*`, "keys", value = c(1L, 0L)) :
replacement has 2 rows, data has 0
I understand that ggvis is very new and constantly developing, but I suspect that there is merely something in Shiny reactive values that is out of sync. If anyone could point out what I'm doing wrong, thanks a lot!
The error is caused because you have a data.frame with zero rows and have a resulting 1:0.
You can change your selected function to:
selected <- reactive({
if (is.null(input$items)) {
return(aalto_all)
}
df <- aalto_all[aalto_all[[input$dim]] %in% input$items, ]
df$keys <-seq_along(df[,1])
if(nrow(df) == 0){
return(aalto_all)
}
df
})