R-Shiny using Reactive renderUI value - r

How do you use values obtained from a renderUI element in a reactive wrapper?
i.e. My code:
CompanyNames <- sqlQuery(connection, "SELECT Companynm FROM RiskMgm_Company")
output$CompNameSelector <- renderUI({
selectInput("compName","Company Name:",as.vector(CompanyNames[,1]))
})
CompID <- reactive({
CompID <<- sqlQuery(paste("SELECT CompanyID FROM RiskMgm_Company WHERE Companynm = '",compName,"'"))
})
output$MotorSelector <- renderUI({
selectInput("MachSer","Machine:",sqlQuery(connection,paste("SELECT Motor_func FROM RiskMgm_Motor WHERE Company_ID='",CompID,"'")))
})
My error:
Successfilly opened connection to db
Error in paste("SELECT CompanyID FROM RiskMgm_Company WHERE Companynm = '", :
could not find function "compName"
What am I doing wrong? Essentially what I want is a list of companies given by the SQL query. Then depending on the Company selected it will show the motors that belong to that company in the next dropdown box
Thanks

You would refer to the elements by their id for example input$compName. As a contrived example here
is a simple shiny app with two selectInput's. The second selectInput choices depend on the value of the first. Referencing the output of widgets created by renderUI is no different from referencing the same widgets if they had been in UI.R from the beginning:
library(shiny)
myDF <- data.frame(A = 1:4, B = 3:6, C = 6:9, D = 10:13)
runApp(
list(
ui = fluidPage(
uiOutput("myList"),
uiOutput("myNumbers")
)
, server = function(input, output, session){
output$myList <- renderUI({
selectInput("compName", "Company Name:", LETTERS[1:4])
})
output$myNumbers <- renderUI({
selectInput("compNo", "Product Line:", myDF[, input$compName])
})
}
)
)

Related

Reactive value does not update when input is first generated

I'm currently trying to develop a large application using modules. One of those module is used to filter a dataset where the user can first select the columns he wants to filter. Once he selects the columns, the user can then select the values for each column.
As it is a two steps process, the option to select the values is not available while no columns have been chosen.
Now, my issue is that when the selectInput used to select values is first generated its value on the server side does not seem to update to the default selection.
Here's an example of what I'm trying to do:
Module UI
filter_ui <- function(id){
ns <- NS(id)
tagList(
uiOutput(outputId = ns("filter")),
uiOutput(outputId = ns("value"))
)
}
Module Server
filter_server <- function(id){
moduleServer( id, function(input, output, session){
ns <- session$ns
mod_values <- reactiveValues()
output$filter <- renderUI({
selectInput(inputId = ns("filter"),
label = "Filter",
multiple = TRUE,
selected = NULL,
choices = list("variable_a",
"variable_b",
"variable_c"))
})
observeEvent(input$filter, {
output$value <- renderUI({
lapply(input$filter, function(i){
selectInput(inputId = ns(i),
label = paste0("Select ",i),
multiple = FALSE,
choices = list("1",
"2",
"3"))
})
})
mod_values$filter <- input$filter
for (j in input$filter) {
mod_values$values[[paste0(j)]] <- input[[paste0(j)]]
}
})
return(mod_values)
})
}
The reason why I'm using uiOutput instead of just a regular selectInput in the UI is because in the application there are other arguments that will influence what is rendered.
App
ui <- function() {
fluidPage(
filter_ui("filter")
)
}
server <- function(input, output, session) {
filter_value <- filter_server("filter")
variable <- reactive({filter_value$filter})
value <- reactive({filter_value$values})
observeEvent(variable(), {
print(value())
print(variable())
req(value())
n <- 0
for (i in variable()) {
n <- n + 1
print(paste0("the ", n, "th loop value is ", value()[[i]]))
}
})
}
shinyApp(ui, server)
Now, the first time I select any filter the value does not update and I get for example:
[1] "variable_a" "variable_c"
[1] "the 1th loop value is 1"
[1] "the 2th loop value is "
While I need:
[1] "variable_a" "variable_c"
[1] "the 1th loop value is 1"
[1] "the 2th loop value is 1"
I guess my issue comes from a wrong use of reactivity but I can't seem to find what. Any help would be greatly appreciated!

Updated codes using Reactive values

I am looking to build one interactive data visualisation.
My dataset contains 1244 obs and 9 variables
sharing a screenshot of data below:
Screenshot of sample Dataset
Flow of data visualisation:
Select the company name from an input box and it will give an output table (subset of that company from main dataset)
Select DIR of the above compary from an input box
After deleting the DIR, it will give an output of the company name (after checking the main dataset), if it is present.
Code which I have written is provided below, but it is not working. I will appreciate valuable input. Thanks in advance.
UI
navbarPage(
title = "SHELL COMPANY",
tabPanel("COMPANY INFO",
fluidRow(
column(4, selectInput("name","COMPANY NAME:", c("ALL", unique(as.character(cmp$`STD COMPANY NAME`))))),
column(4, DT::dataTableOutput("table")
))),
tabPanel("DIR INFO",
fluidRow(
column(4, selectInput("dir","DIRECTOR NAME:", sort(unique(as.character(cmp$`DIR NAME`)))))),
column(4, DT::dataTableOutput("table2"))
))
SERVER
function(input,output)
{
data <- cmp
rv <- reactiveValues()
observe({
rv$table <- cmp
if(input$name!="ALL"){
rv$table <- data[data$`STD COMPANY NAME`==input$name,]
}
})
output$table <- DT::renderDataTable(DT::datatable(
{
rv$table
}))
output$table2 <- DT::renderDataTable(DT::datatable(
{
data2 <- rv$table
data2 <- subset(rv$table, data$'DIR NAME'==input$dir, select=c(`STD COMPANY NAME`, `DIR NAME`))
data2
}))}
If the snippet that you provided is all you've got in the app concerning the error, it seems that you try to assign output$table to another variable inside output$table2 at data2 <- table. You can't assign output$... like that. Try creating separate table (?reactiveValues() might come in handy), and use it in both outputs, so the logic looks like this:
rv <- reactiveValues()
observe({
rv$table <- cmp
if(input$name!="ALL"){
rv$table <- data[data$`STD COMPANY NAME`==input$name,]
}
})
Then use it in both output$table and output$table2

R-Shiny UI idiom for multi-select input with number pair

I need to allow the user to select some widgets from a fixed set of widgets and then enter a quantity for each widget he has selected.
selectInput("widgets","Widgets",choices = widgets_list,multiple = TRUE)
How can I show a set of Numeric Entry boxes dynamically, one for each item selected by the user in the multi-select box above?
Eventually I want to end up with some structure like:
data.frame(widgets=c("Widget1","Widget2","Widget3"),quantities=c(23,34,23))
Any thoughts on how best to implement this?
Here is a toy program that does what you want - I think.
It uses a reactiveValues to declare a pair of vectors that you can then be changed reactively. It uses renderUI and uiOutput to render new input devices as the underlying data changes. It also uses renderDataTable to show you the data table that is being created.
library(shiny)
widgets_list = c("Widget1","Widget2","Widget3")
widgets_quan = c(23,34,23)
u <- shinyUI(fluidPage(
titlePanel("Shiny Widgets Input"),
sidebarLayout(position = "left",
sidebarPanel(h3("sidebar panel"),
uiOutput("widgname"),
uiOutput("widgquan")
),
mainPanel(h3("main panel"),
dataTableOutput("dataframe")
)
)))
s <- shinyServer(function(input,output) {
rv <- reactiveValues(wname = widgets_list,wquan = widgets_quan)
observeEvent(input$widgquan, {
rv$wquan[ which(rv$wname==input$widget) ] <- input$widgquan
})
output$widgname <- renderUI({
selectInput("widget","Widget",choices = rv$wname)
})
output$widgquan <- renderUI({
req(input$widget)
n <- rv$wquan[which(rv$wname == input$widget)]
numericInput("widgquan","Quantity:",n)
})
widgdata <- reactive({
req(input$widgquan)
df <- data.frame(Widgets = rv$wname,Quantity = rv$wquan)
})
output$dataframe <- renderDataTable({ widgdata() })
})
shinyApp(ui = u,server = s)
yielding:

R Shiny: How to dynamically append arbitrary number of input widgets

The goal
I am working on a Shiny app that allows the user to upload their own data and focus on the entire data or a subset by providing data filtering widgets described by the below graph
The select input "Variable 1" will display all the column names of the data uploaded by the user and the selectize input "Value" will display all the unique values of the corresponding column selected in "Variable 1". Ideally, the user will be able to add as many such rows ("Variable X" + "Value") as possible by some sort of trigger, one possibility being clicking the "Add more" action button.
A possible solution
After looking up online, I've found one promising solution given by Nick Carchedi pasted below
ui.R
library(shiny)
shinyUI(pageWithSidebar(
# Application title
headerPanel("Dynamically append arbitrary number of inputs"),
# Sidebar with a slider input for number of bins
sidebarPanel(
uiOutput("allInputs"),
actionButton("appendInput", "Append Input")
),
# Show a plot of the generated distribution
mainPanel(
p("The crux of the problem is to dynamically add an arbitrary number of inputs
without resetting the values of existing inputs each time a new input is added.
For example, add a new input, set the new input's value to Option 2, then add
another input. Note that the value of the first input resets to Option 1."),
p("I suppose one hack would be to store the values of all existing inputs prior
to adding a new input. Then,", code("updateSelectInput()"), "could be used to
return inputs to their previously set values, but I'm wondering if there is a
more efficient method of doing this.")
)
))
server.R
library(shiny)
shinyServer(function(input, output) {
# Initialize list of inputs
inputTagList <- tagList()
output$allInputs <- renderUI({
# Get value of button, which represents number of times pressed
# (i.e. number of inputs added)
i <- input$appendInput
# Return if button not pressed yet
if(is.null(i) || i < 1) return()
# Define unique input id and label
newInputId <- paste0("input", i)
newInputLabel <- paste("Input", i)
# Define new input
newInput <- selectInput(newInputId, newInputLabel,
c("Option 1", "Option 2", "Option 3"))
# Append new input to list of existing inputs
inputTagList <<- tagAppendChild(inputTagList, newInput)
# Return updated list of inputs
inputTagList
})
})
The downside
As pointed by Nick Carchedi himself, all the existing input widgets will undesirably get reset every time when a new one is added.
A promising solution for data subsetting/filtering in Shiny
As suggested by warmoverflow, the datatable function in DT package provides a nice way to filter the data in Shiny. See below a minimal example with data filtering enabled.
library(shiny)
shinyApp(
ui = fluidPage(DT::dataTableOutput('tbl')),
server = function(input, output) {
output$tbl = DT::renderDataTable(
iris, filter = 'top', options = list(autoWidth = TRUE)
)
}
)
If you are going to use it in your Shiny app, there are some important aspects that are worth noting.
Filtering box type
For numeric/date/time columns: range sliders are used to filter rows within ranges
For factor columns: selectize inputs are used to display all possible categories
For character columns: ordinary search boxes are used
How to obtain the filtered data
Suppose the table output id is tableId, use input$tableId_rows_all as the indices of rows on all pages (after the table is filtered by the search strings). Please note that input$tableId_rows_all returns the indices of rows on all pages for DT (>= 0.1.26). If you use the DT version by regular install.packages('DT'), only the indices of the current page are returned
To install DT (>= 0.1.26), refer to its GitHub page
Column width
If the data have many columns, column width and filter box width will be narrow, which makes it hard to see the text as report here
Still to be solved
Despite some known issues, datatable in DT package stands as a promising solution for data subsetting in Shiny. The question itself, i.e. how to dynamically append arbitrary number of input widgets in Shiny, nevertheless, is interesting and also challenging. Until people find a good way to solve it, I will leave this question open :)
Thank you!
are you looking for something like this?
library(shiny)
LHSchoices <- c("X1", "X2", "X3", "X4")
#------------------------------------------------------------------------------#
# MODULE UI ----
variablesUI <- function(id, number) {
ns <- NS(id)
tagList(
fluidRow(
column(6,
selectInput(ns("variable"),
paste0("Select Variable ", number),
choices = c("Choose" = "", LHSchoices)
)
),
column(6,
numericInput(ns("value.variable"),
label = paste0("Value ", number),
value = 0, min = 0
)
)
)
)
}
#------------------------------------------------------------------------------#
# MODULE SERVER ----
variables <- function(input, output, session, variable.number){
reactive({
req(input$variable, input$value.variable)
# Create Pair: variable and its value
df <- data.frame(
"variable.number" = variable.number,
"variable" = input$variable,
"value" = input$value.variable,
stringsAsFactors = FALSE
)
return(df)
})
}
#------------------------------------------------------------------------------#
# Shiny UI ----
ui <- fixedPage(
verbatimTextOutput("test1"),
tableOutput("test2"),
variablesUI("var1", 1),
h5(""),
actionButton("insertBtn", "Add another line")
)
# Shiny Server ----
server <- function(input, output) {
add.variable <- reactiveValues()
add.variable$df <- data.frame("variable.number" = numeric(0),
"variable" = character(0),
"value" = numeric(0),
stringsAsFactors = FALSE)
var1 <- callModule(variables, paste0("var", 1), 1)
observe(add.variable$df[1, ] <- var1())
observeEvent(input$insertBtn, {
btn <- sum(input$insertBtn, 1)
insertUI(
selector = "h5",
where = "beforeEnd",
ui = tagList(
variablesUI(paste0("var", btn), btn)
)
)
newline <- callModule(variables, paste0("var", btn), btn)
observeEvent(newline(), {
add.variable$df[btn, ] <- newline()
})
})
output$test1 <- renderPrint({
print(add.variable$df)
})
output$test2 <- renderTable({
add.variable$df
})
}
#------------------------------------------------------------------------------#
shinyApp(ui, server)
Now, I think that I understand better the problem.
Suppose the user selects the datasets::airquality dataset (here, I'm showing only the first 10 rows):
The field 'Select Variable 1' shows all the possible variables based on the column names of said dataset:
Then, the user selects the condition and the value to filter the dataset by:
Then, we want to add a second filter (still maintaining the first one):
Finally, we get the dataset filtered by the two conditions:
If we want to add a third filter:
You can keep adding filters until you run out of data.
You can also change the conditions to accommodate factors or character variables. All you need to do is change the selectInput and numericInput to whatever you want.
If this is what you want, I've solved it using modules and by creating a reactiveValue (tmpFilters) that contains all selections (variable + condition + value). From it, I created a list with all filters (tmpList) and from it I created the proper filter (tmpListFilters) to use with subset.
This works because the final dataset is "constantly" being subset by this reactiveValue (the tmpFilters). At the beginning, tmpFilters is empty, so we get the original dataset. Whenever the user adds the first filter (and other filters after that), this reactiveValue gets updated and so does the dataset.
Here's the code for it:
library(shiny)
# > MODULE #####################################################################
## |__ MODULE UI ===============================================================
variablesUI <- function(id, number, LHSchoices) {
ns <- NS(id)
tagList(
fluidRow(
column(
width = 4,
selectInput(
inputId = ns("variable"),
label = paste0("Select Variable ", number),
choices = c("Choose" = "", LHSchoices)
)
),
column(
width = 4,
selectInput(
inputId = ns("condition"),
label = paste0("Select condition ", number),
choices = c("Choose" = "", c("==", "!=", ">", ">=", "<", "<="))
)
),
column(
width = 4,
numericInput(
inputId = ns("value.variable"),
label = paste0("Value ", number),
value = NA,
min = 0
)
)
)
)
}
## |__ MODULE SERVER ===========================================================
filter <- function(input, output, session){
reactive({
req(input$variable, input$condition, input$value.variable)
fullFilter <- paste0(
input$variable,
input$condition,
input$value.variable
)
return(fullFilter)
})
}
# Shiny ########################################################################
## |__ UI ======================================================================
ui <- fixedPage(
fixedRow(
column(
width = 5,
selectInput(
inputId = "userDataset",
label = paste0("Select dataset"),
choices = c("Choose" = "", ls("package:datasets"))
),
h5(""),
actionButton("insertBtn", "Add another filter")
),
column(
width = 7,
tableOutput("finalTable")
)
)
)
## |__ Server ==================================================================
server <- function(input, output) {
### \__ Get dataset from user selection ------------------------------------
originalDF <- reactive({
req(input$userDataset)
tmpData <- eval(parse(text = paste0("datasets::", input$userDataset)))
if (!class(tmpData) == "data.frame") {
stop("Please select a dataset of class data.frame")
}
tmpData
})
### \__ Get the column names -----------------------------------------------
columnNames <- reactive({
req(input$userDataset)
tmpData <- eval(parse(text = paste0("datasets::", input$userDataset)))
names(tmpData)
})
### \__ Create Reactive Filter ---------------------------------------------
tmpFilters <- reactiveValues()
### \__ First UI Element ---------------------------------------------------
### Add first UI element with column names
observeEvent(input$userDataset, {
insertUI(
selector = "h5",
where = "beforeEnd",
ui = tagList(variablesUI(paste0("var", 1), 1, columnNames()))
)
})
### Update Reactive Filter with first filter
filter01 <- callModule(filter, paste0("var", 1))
observe(tmpFilters[['1']] <- filter01())
### \__ Other UI Elements --------------------------------------------------
### Add other UI elements with column names and update the filter
observeEvent(input$insertBtn, {
btn <- sum(input$insertBtn, 1)
insertUI(
selector = "h5",
where = "beforeEnd",
ui = tagList(variablesUI(paste0("var", btn), btn, columnNames()))
)
newFilter <- callModule(filter, paste0("var", btn))
observeEvent(newFilter(), {
tmpFilters[[paste0("'", btn, "'")]] <- newFilter()
})
})
### \__ Dataset with Filtered Results --------------------------------------
resultsFiltered <- reactive({
req(filter01())
tmpDF <- originalDF()
tmpList <- reactiveValuesToList(tmpFilters)
if (length(tmpList) > 1) {
tmpListFilters <- paste(tmpList, "", collapse = "& ")
} else {
tmpListFilters <- unlist(tmpList)
}
tmpResult <- subset(tmpDF, eval(parse(text = tmpListFilters)))
tmpResult
})
### \__ Print the Dataset with Filtered Results ----------------------------
output$finalTable <- renderTable({
req(input$userDataset)
if (is.null(tmpFilters[['1']])) {
head(originalDF(), 10)
} else {
head(resultsFiltered(), 10)
}
})
}
#------------------------------------------------------------------------------#
shinyApp(ui, server)
# End
If you are looking for a data subsetting/filtering in Shiny Module :
filterData from package shinytools can do the work. It returns an expression as a call but it can also return the data (if your dataset is not too big).
library(shiny)
# remotes::install_github("ardata-fr/shinytools")
library(shinytools)
ui <- fluidPage(
fluidRow(
column(
3,
filterDataUI(id = "ex"),
actionButton("AB", label = "Apply filters")
),
column(
3,
tags$strong("Expression"),
verbatimTextOutput("expression"),
tags$br(),
DT::dataTableOutput("DT")
)
)
)
server <- function(input, output) {
x <- reactive({iris})
res <- callModule(module = filterDataServer, id = "ex", x = x, return_data = FALSE)
output$expression <- renderPrint({
print(res$expr)
})
output$DT <- DT::renderDataTable({
datatable(data_filtered())
})
data_filtered <- eventReactive(input$AB, {
filters <- eval(expr = res$expr, envir = x())
x()[filters,]
})
}
shinyApp(ui, server)
You can also use lazyeval or rlang to evaluate the expression :
filters <- lazyeval::lazy_eval(res$expr, data = x())
filters <- rlang::eval_tidy(res$expr, data = x())
You need to check for existing input values and use them if available:
# Prevent dynamic inputs from resetting
newInputValue <- "Option 1"
if (newInputId %in% names(input)) {
newInputValue <- input[[newInputId]]
}
# Define new input
newInput <- selectInput(newInputId, newInputLabel, c("Option 1", "Option 2", "Option 3"), selected=newInputValue)
A working version of the gist (without the reset problem) can be found here: https://gist.github.com/motin/0d0ed0d98fb423dbcb95c2760cda3a30
Copied below:
ui.R
library(shiny)
shinyUI(pageWithSidebar(
# Application title
headerPanel("Dynamically append arbitrary number of inputs"),
# Sidebar with a slider input for number of bins
sidebarPanel(
uiOutput("allInputs"),
actionButton("appendInput", "Append Input")
),
# Show a plot of the generated distribution
mainPanel(
p("This shows how to add an arbitrary number of inputs
without resetting the values of existing inputs each time a new input is added.
For example, add a new input, set the new input's value to Option 2, then add
another input. Note that the value of the first input does not reset to Option 1.")
)
))
server.R
library(shiny)
shinyServer(function(input, output) {
output$allInputs <- renderUI({
# Get value of button, which represents number of times pressed (i.e. number of inputs added)
inputsToShow <- input$appendInput
# Return if button not pressed yet
if(is.null(inputsToShow) || inputsToShow < 1) return()
# Initialize list of inputs
inputTagList <- tagList()
# Populate the list of inputs
lapply(1:inputsToShow,function(i){
# Define unique input id and label
newInputId <- paste0("input", i)
newInputLabel <- paste("Input", i)
# Prevent dynamic inputs from resetting
newInputValue <- "Option 1"
if (newInputId %in% names(input)) {
newInputValue <- input[[newInputId]]
}
# Define new input
newInput <- selectInput(newInputId, newInputLabel, c("Option 1", "Option 2", "Option 3"), selected=newInputValue)
# Append new input to list of existing inputs
inputTagList <<- tagAppendChild(inputTagList, newInput)
})
# Return updated list of inputs
inputTagList
})
})
(The solution was guided on Nick's hints in the original gist from where you got the code of the promising solution)

Shiny - renaming factors in reactive data frame

I'm building a shiny app that queries an SQL database so the user can ggplot the data. I would like the user to be able to rename factors manually but am struggling to get going. Here is an example of what I want to do:
ui.R
library(markdown)
shinyUI(fluidPage(
titlePanel("Reactive factor label"),
sidebarLayout(
sidebarPanel(
numericInput("wafer", label = h3("Input wafer ID:"), value = NULL),
actionButton("do", "Search wafer"),
textInput("text", label = h3("Factor name to change"), value = ""),
textInput("text", label = h3("New factor name"), value = ""),
actionButton("do2", "Change name")
),
mainPanel(
verbatimTextOutput("waf"),
verbatimTextOutput("que"),
verbatimTextOutput("pos"),
dataTableOutput(outputId="tstat")
)
)
)
)
server.R
# Create example data
Name <- factor(c("Happy", "New", "Year"))
Id <- 1:3
dd <- data.frame(Id, Name)
con <- dbConnect(RSQLite::SQLite(), ":memory:")
dbWriteTable(con, "dd", dd)
query <- function(...) dbGetQuery(con, ...)
wq = data.frame()
sq = data.frame()
shinyServer(function(input, output){
# create data frame to store reactive data set from query
values <- reactiveValues()
values$df <- data.frame()
# Wait for user to search
d <- eventReactive(input$do, { input$wafer })
# Reactive SQL query
a <- reactive({ paste0("Select * from dd where Id=",d()) })
wq <- reactive({ query( a() ) })
# Check outputs
output$waf <- renderPrint(input$wafer)
output$que <- renderPrint({ a() })
output$pos <- renderPrint( wq()[1,1] )
# observe d() so that data is not added until user presses action button
observe({
if (!is.null(d())) {
sq <- reactive({ query( a() ) })
# add query to reactive data frame
values$df <- rbind(isolate(values$df), sq())
}
})
output$tstat <- renderDataTable({
data <- values$df
})
})
In static R I would normally use data table to rename factors i.e.:
DT <- data.table(df)
DT[Name=="Happy", Name:="Sad"]
But I'm not sure how to go about this with a reactiveValues i.e. values$df.
I have read this (R shiny: How to get an reactive data frame updated each time pressing an actionButton without creating a new reactive data frame?). This lead me to try this but it doesn't do anything (even no error):
observeEvent(input$do2, {
DT <- data.table(values$df)
DT[Name == input$text1, Name := input$text2]
values$df <- data.frame(values$df)
})
Perhaps there is a way around this..maybe there is a way to use an action button to "lock in" the data as a new data frame, which can then be used to rename?
Sorry for such a long winded question. My real app is much longer and more complex. I have tried to strip it down.
Your approach works but there are a few issues in your app.
In ui.R, both textInput have the same id, they need to be different so you can refer to them in the server.R. In the observeEvent you posted, you refer to input$text1 and input$text2 so you should change the id of the textInputs to text1 and text2.
In the observeEvent you posted, the last line should be values$df <- as.data.frame(DT), otherwise it does not change anything.

Resources