Use insertUI to create different kind of shiny widgets - r

I have the shiny app below in which the user may select between one or more column names from the data frame.
name<-c("John","Jack","Bill")
value1<-c(2,4,6)
add<-c("SDF","GHK","FGH")
value2<-c(3,4,5)
dt<-data.frame(name,value1,add,value2)
Then for every selection he makes the relative pickerInput() may be displayed below. The issue is that I would like to set a diffrent widget for specific columns. Let's say that I would like to set those with numeric values as sliderInput(). I have 2 versions below of the same app. So if any solution is applicable to on of them it would be ok.
app1
library(shiny)
library(shinyWidgets)
library(DT)
# ui object
ui <- fluidPage(
titlePanel(p("Spatial app", style = "color:#3474A7")),
sidebarLayout(
sidebarPanel(
pickerInput(
inputId = "p1",
label = "Select Column headers",
choices = colnames( dt),
multiple = TRUE,
options = list(`actions-box` = TRUE)
),
#Add the output for new pickers
uiOutput("pickers")
),
mainPanel(
)
)
)
# server()
server <- function(input, output) {
observeEvent(input$p1, {
#Create the new pickers
output$pickers<-renderUI({
div(lapply(input$p1, function(x){
pickerInput(
inputId = x#The colname of selected column
,
label = x #The colname of selected column
,
choices = dt[,x]#all rows of selected column
,
multiple = TRUE,
options = list(`actions-box` = TRUE)
)
}))
})
})
}
# shinyApp()
shinyApp(ui = ui, server = server)
app2
library(shiny)
library(shinyWidgets)
library(DT)
name<-c("John","Jack","Bill")
value1<-c(2,4,6)
add<-c("SDF","GHK","FGH")
value2<-c(3,4,5)
dt<-data.frame(name,value1,add,value2)
# ui object
ui <- fluidPage(
titlePanel(p("Spatial app", style = "color:#3474A7")),
sidebarLayout(
sidebarPanel(
pickerInput(
inputId = "p1",
label = "Select Column headers",
choices = colnames( dt),
multiple = TRUE,
options = list(`actions-box` = TRUE)
),
tags$div(id = "add_ui_here")
),
mainPanel(
)
)
)
# server()
server <- function(input, output) {
# store currently selected columns
selected_columns <- c()
observeEvent(input$p1, {
# determine pickerInputs to remove
input_remove <- !selected_columns %in% input$p1
input_remove <- selected_columns[input_remove]
# remove inputs
if (!is.null(input_remove) && length(input_remove) > 0) {
for (input_element in input_remove) {
removeUI(selector = paste0("#", input_element, "_remove_id"))
}
}
# determine pickerInputs to add
input_add <- !input$p1 %in% selected_columns
input_add <- input$p1[input_add]
# add inputs
if (length(input_add) > 0) {
for (input_element in input_add) {
insertUI(
selector = "#add_ui_here",
where = "afterEnd",
ui = tags$div(id = paste0(input_element, "_remove_id"),
pickerInput(
inputId = input_element
,
label = input_element
,
choices = dt[, input_element]
,
multiple = TRUE,
options = list(`actions-box` = TRUE)
))
)
}
}
# update the currently stored column variable
selected_columns <<- input$p1
},
ignoreNULL = FALSE)
}
# shinyApp()
shinyApp(ui = ui, server = server)

Check if the selected variable is numeric or character and assign the appropriate widget. Try this code.
name<-c("John","Jack","Bill")
value1<-c(2,4,6)
add<-c("SDF","GHK","FGH")
value2<-c(3,4,5)
dt<-data.frame(name,value1,add,value2)
# ui object
ui <- fluidPage(
titlePanel(p("Spatial app", style = "color:#3474A7")),
sidebarLayout(
sidebarPanel(
pickerInput(
inputId = "p1",
label = "Select Column headers",
choices = colnames( dt),
multiple = TRUE,
options = list(`actions-box` = TRUE)
),
#Add the output for new pickers
uiOutput("pickers")
),
mainPanel(
)
)
)
# server()
server <- function(input, output) {
observeEvent(input$p1, {
#Create the new pickers
output$pickers<-renderUI({
div(lapply(input$p1, function(x){
if (is.numeric(dt[[x]])) {
sliderInput(inputId=x, label=x, min=min(dt[x]), max=max(dt[[x]]), value=min(dt[[x]]))
}
else if (is.character(dt[[x]])) {
pickerInput(
inputId = x#The colname of selected column
,
label = x #The colname of selected column
,
choices = dt[,x]#all rows of selected column
,
multiple = TRUE,
options = list(`actions-box` = TRUE)
)
}
}))
})
})
}
# shinyApp()
shinyApp(ui = ui, server = server)

Related

Dynamically update two selectInput boxes based on the others selection in R Shiny module is not working

I have two selectInput boxes in my ShinyApp. Both of them take the same inputs, i.e., the column names of an uploaded table.
I want to make the two input box mutually exclusive, meaning if a column name is selected in one input box, it will become unavailable in the second input box, and vice versa.
Here is my code, and it works.
library(shiny)
ui <- fluidPage(
fileInput(inputId = "rawFile",
label = "Upload Data Table:",
multiple = FALSE,
accept = c(".csv")
),
uiOutput(outputId = "v1",
label = "Select Variable 1"
),
uiOutput(outputId = "v2",
label = "Select Variable 2"
)
)
server <- function(input, output, session){
inputData <- reactive({
inFile <- input$rawFile
if(is.null(inFile)){return(NULL)}
extension <- tools::file_ext(inFile$name)
filepath <- inFile$datapath
df <- read.csv(filepath, header = TRUE)
return(df)
})
output$v1 <- renderUI({
shiny::req(inputData())
selectInput(inputId = "v1",
label = "Select columns to remove",
multiple = TRUE,
choices = names(inputData())
)
})
output$v2 <- renderUI({
shiny::req(inputData())
selectInput(inputId = "v2",
label = "Select columns to remove",
multiple = TRUE,
choices = names(inputData())
)
})
observe({
if(!is.null(input$v2))
updateSelectInput(session, "v1",
choices = names(inputData())[!(names(inputData()) %in% input$v2)],
selected = isolate(input$v1)
)
})
observe({
if(!is.null(input$v1))
updateSelectInput(session, "v2",
choices = names(inputData())[!(names(inputData()) %in% input$v1)],
selected = isolate(input$v2)
)
})
}
shinyApp(ui = ui, server = server)
But when I put this code in a module, it is not working. I don't where the problem is.
library(shiny)
ui_1 <- function(id){
ns <- NS(id)
tagList(
fluidPage(
fileInput(inputId = ns("rawFile"),
label = "Upload Data Table:",
multiple = FALSE,
accept = c(".csv")
),
uiOutput(outputId = ns("v1"),
label = "Select Variable 1"
),
uiOutput(outputId = ns("v2"),
label = "Select Variable 2"
)
)
)
}
server_1 <- function(id){
moduleServer( id, function(input, output, session){
ns <- session$ns
inputData <- reactive({
inFile <- input$rawFile
if(is.null(inFile)){return(NULL)}
extension <- tools::file_ext(inFile$name)
filepath <- inFile$datapath
df <- read.csv(filepath, header = TRUE)
return(df)
})
output$v1 <- renderUI({
shiny::req(inputData())
selectInput(inputId = ns("v1"),
label = "Select columns to remove",
multiple = TRUE,
choices = names(inputData())
)
})
output$v2 <- renderUI({
shiny::req(inputData())
selectInput(inputId = ns("v2"),
label = "Select columns to remove",
multiple = TRUE,
choices = names(inputData())
)
})
observe({
if(!is.null(input$v2))
updateSelectInput(session, ns("v1"),
choices = names(inputData())[!(names(inputData()) %in% input$v2)],
selected = isolate(input$v1)
)
})
observe({
if(!is.null(input$v1))
updateSelectInput(session, ns("v2"),
choices = names(inputData())[!(names(inputData()) %in% input$v1)],
selected = isolate(input$v2)
)
})
}
)
}
The issue is that you wrapped the input id's in ns() inside your updateSelectInputs. You have to do so in renderUI only.
Note: I replaced the code to read a file with mtcars.
library(shiny)
ui_1 <- function(id) {
ns <- NS(id)
tagList(
fluidPage(
fileInput(
inputId = ns("rawFile"),
label = "Upload Data Table:",
multiple = FALSE,
accept = c(".csv")
),
uiOutput(
outputId = ns("v1"),
label = "Select Variable 1"
),
uiOutput(
outputId = ns("v2"),
label = "Select Variable 2"
)
)
)
}
server_1 <- function(id) {
moduleServer(id, function(input, output, session) {
ns <- session$ns
inputData <- reactive({
mtcars
})
output$v1 <- renderUI({
shiny::req(inputData())
selectInput(
inputId = ns("v1"),
label = "Select columns to remove",
multiple = TRUE,
choices = names(inputData())
)
})
output$v2 <- renderUI({
shiny::req(inputData())
selectInput(
inputId = ns("v2"),
label = "Select columns to remove",
multiple = TRUE,
choices = names(inputData())
)
})
observe({
if (!is.null(input$v2)) {
updateSelectInput(session, "v1",
choices = names(inputData())[!(names(inputData()) %in% input$v2)],
selected = isolate(input$v1)
)
}
})
observe({
if (!is.null(input$v1)) {
updateSelectInput(session, "v2",
choices = names(inputData())[!(names(inputData()) %in% input$v1)],
selected = isolate(input$v2)
)
}
})
})
}
ui <- fluidPage(
ui_1("foo")
)
server <- function(input, output, session) {
server_1("foo")
}
shinyApp(ui, server)

Change color of slider using updateSliderTextInput

I am trying to change the color of the slide when updating its values. I have tried different ways without success. The following code does not run, but replicates what I am trying to do:
if (interactive()) {
library("shiny")
library("shinyWidgets")
ui <- fluidPage(
br(),
sliderTextInput(
inputId = "mySlider",
label = "Pick a month :",
choices = month.abb,
selected = "Jan"
),
verbatimTextOutput(outputId = "res"),
radioButtons(
inputId = "up",
label = "Update choices:",
choices = c("Abbreviations", "Full names")
)
)
server <- function(input, output, session) {
output$res <- renderPrint(str(input$mySlider))
observeEvent(input$up, {
choices <- switch(
input$up,
"Abbreviations" = month.abb,
"Full names" = month.name
)
updateSliderTextInput(
session = session,
inputId = "mySlider",
choices = choices,
color = "red" # This is the line I need to add
)
}, ignoreInit = TRUE)
}
shinyApp(ui = ui, server = server)
}
Maybe has someone the answer to this?
I was able to give this some more thought and figured out a way to update the slider color based on an input. shinyWidgets::setSliderColor essentially just injects CSS to overwrite all the classes associated with the sliderInputs. So it needs to be included in the UI instead of the server. (Took a min to realize that).
I set up a blank uiOutput which is then updated by observing input$up with the new or default color.
Demo
ui <- fluidPage(
br(),
mainPanel(class = "temp",
uiOutput('s_color'), # uiOuput
sliderTextInput(
inputId = "mySlider",
label = "Pick a month :",
choices = month.abb,
selected = "Jan"
),
verbatimTextOutput(outputId = "res"),
radioButtons(
inputId = "up",
label = "Update choices:",
choices = c("Abbreviations", "Full names")
)
)
)
server <- function(input, output, session) {
output$res <- renderPrint(str(input$mySlider))
# output$s_color = renderUI({})
observeEvent(input$up, {
choices <- switch(
input$up,
"Abbreviations" = month.abb,
"Full names" = month.name
)
updateSliderTextInput(
session = session,
inputId = "mySlider",
choices = choices
)
output$s_color = renderUI({ # add color
if (input$up == "Full names") {
setSliderColor(c("Red"), c(1))
} else {
setSliderColor(c("#428bca"), c(1))
}
})
}, ignoreInit = TRUE)
}
shinyApp(ui = ui, server = server)

Is there a way to make selectInput, dateInput and the "filter = 'top'" argument in datatable to work in the same R Shiny app?

I am trying to make an app similar to this one using R Shiny, but my form needs to contain multiple inputs using inputDate, selectInput and selectizeInput and my table needs to include conditional formatting (implemented here using formatStyle) and be filterable by column (filter = 'top').
The form in this app, with a selectInput, a dateInput and no column filters on the table, works as expected:
library(shiny)
library(dplyr)
library(DT)
## 1: select input, date input, no filter
ui1 <- fluidPage(
fluidRow(
actionButton("add_button", "Add", icon("plus"))
),
br(),
fluidRow(
dataTableOutput('tbl')
)
)
server1 <- function(input, output) {
data <- data.frame(
ID = c(1,2,3),
Date = as.Date(c('2022-11-13','2022-11-14','2022-11-15')),
RAG = c('Red','Amber','Green')
)
output$tbl <- renderDataTable(
datatable(data, rownames = FALSE) %>%
formatStyle('RAG', target = 'cell', backgroundColor = styleEqual(
c('Red','Amber','Green'),c('#d2222d','#ffbf00','#238823')
))
)
observeEvent(input$add_button, priority = 20,{
showModal(
modalDialog(
fluidPage(
textInput('ID', 'ID:'),
dateInput('Date', 'Date:'),
selectInput('RAG', 'RAG:', choices = c('Red','Amber','Green'))
)))
})
}
# Run the application
shinyApp(ui = ui1, server = server1)
As does the form in this app, which has a dateInput and column filters but no selectInput:
library(shiny)
library(dplyr)
library(DT)
## 2: date input, filter, no select input
ui2 <- fluidPage(
fluidRow(
actionButton("add_button", "Add", icon("plus"))
),
br(),
fluidRow(
dataTableOutput('tbl')
)
)
server2 <- function(input, output) {
data <- data.frame(
ID = c(1,2,3),
Date = as.Date(c('2022-11-13','2022-11-14','2022-11-15')),
RAG = c('Red','Amber','Green')
)
output$tbl <- renderDataTable(
datatable(data, rownames = FALSE, filter = 'top'
) %>%
formatStyle('RAG', target = 'cell', backgroundColor = styleEqual(
c('Red','Amber','Green'),c('#d2222d','#ffbf00','#238823')
))
)
observeEvent(input$add_button, priority = 20,{
showModal(
modalDialog(
fluidPage(
textInput('ID', 'ID:'),
dateInput('Date', 'Date:'),
textInput('RAG', 'RAG:')
)))
})
}
# Run the application
shinyApp(ui = ui2, server = server2)
However, when I include a selectInput, dateInput and column filters, the dateInput and selectInput fields do not function as they should:
library(shiny)
library(dplyr)
library(DT)
## 3: select input, date input, filter
ui3 <- fluidPage(
fluidRow(
actionButton("add_button", "Add", icon("plus"))
),
br(),
fluidRow(
dataTableOutput('tbl')
)
)
server3 <- function(input, output) {
data <- data.frame(
ID = c(1,2,3),
Date = as.Date(c('2022-11-13','2022-11-14','2022-11-15')),
RAG = c('Red','Amber','Green')
)
output$tbl <- renderDataTable(
datatable(data, rownames = FALSE, filter = 'top'
) %>%
formatStyle('RAG', target = 'cell', backgroundColor = styleEqual(
c('Red','Amber','Green'),c('#d2222d','#ffbf00','#238823')
))
)
observeEvent(input$add_button, priority = 20,{
showModal(
modalDialog(
fluidPage(
textInput('ID', 'ID:'),
dateInput('Date', 'Date:'),
selectInput('RAG', 'RAG:', choices = c('Red','Amber','Green'))
)))
})
}
# Run the application
shinyApp(ui = ui3, server = server3)
Is there a way to include all of the features described in my app?

Unique sidebar inputs for each new dynamic tab created in Shiny

I would like to have unique user inputs for each newly created tab in Shiny, however once the user selects the inputs it stores and does not change for the additional tabs created.
Scenario:
User selected data from local computer
User makes selection from drop down list
Click on Add new tab
Click on the new tab
User custom input = graph changes dynamically
Go back to homepage select new data and Click on Add new tab
Click on the new tab
User custom input = graph does not change and changes as per user input from step 5
Data: Any simple csv table with two columns A and B will replicate the result below
Desired result: Each tab has unique user input and changes the active tab graph dynamically
Section of code where I think the problem is: At lines 68 and 120. Is there a way to set unique inputs for each ammended tab?
Thanks for looking into my problem.
library(shiny)
library(plyr)
library(dplyr)
library(DT)
library(shinyjs)
library(data.table)
library(ggplot2)
ui <- fluidPage(
useShinyjs(),
navbarPage(title = "Test", id = "tabs",
tabPanel("Home",
sidebarPanel(
fileInput("file", "Upload data",
accept = c(
"text/csv",
"text/comma-separated-values,text/plain",
".csv")
),
checkboxInput("header", "Header", TRUE),
actionButton("append", "Add new tab"),
uiOutput('tabnamesui')
),
mainPanel(
)
)
)
)
server <- function(input, output, session) {
userfile <- reactive({
input$file
})
filereact <- reactive({
read.table(
file = userfile()$datapath,
sep = ',',
header = T,
stringsAsFactors = T
)
})
tabsnames <- reactive({
names(filereact())
})
output$tabnamesui <- renderUI({
req(userfile())
selectInput(
'tabnamesui',
h5('Tab names'),
choices = as.list(tabsnames()),
selected="",multiple = FALSE
)
})
tabnamesinput <- reactive({
input$tabnamesui})
#Append selected tab logic
observeEvent(input$append,{
appendTab(inputId = "tabs",
tabPanel(input$tabnamesui,
sidebarPanel(
actionButton(paste0("remove_", input$tabnamesui), "Delete"),
textInput("x", "X-axis label"),
textInput("titlename", "Title"),
sliderInput("bins", "Number of bins", value = 50, min = 1, max = 100)
),
mainPanel(
plotOutput(paste0("dp2",input$tabnamesui))
)
)
)
})
# Delete selected tab logic
observeEvent(lapply(grep(pattern = "^remove_", x = names(input), value = TRUE), function(x){input[[x]]}),{
if(input$tabs != "Home"){
if (input[[paste0("remove_",input$tabs)]]) { ## remove tab only if delete button has been clicked
removeTab(inputId = "tabs", target = input$tabs)
updateSelectInput(session, "tabnamesui", selected = input$tabnamesui) # keep the selection when re-rendering sidebarPanel
}
}
})
#New tab logic to prevent inserting same tab twice with enable/disable action button
forcecombine = function(idtab,checker) {
colnames(idtab) = colnames(checker)
rbind(idtab,checker)
}
checker<-as.data.frame("checker")
idtab<-as.data.frame("checkers")
#only allow tab entry once
observeEvent(input$append, {
idtab <- paste0(tabnamesinput())
idtab<-as.data.frame(idtab)
checkerx<-forcecombine(idtab,checker)
repeated<-length(grep(idtab,checkerx))
if(repeated==1)
{
shinyjs::disable("append")
}
else {shinyjs::enable("append")
}
})
observeEvent(input$tabnamesui, {
shinyjs::enable("append")
lapply(tabnamesinput(), function(x) {
df <- as.data.table(filereact()[[as.name(tabnamesinput())]])
output[[paste0("dp2",input$tabnamesui)]] <- renderPlot({
bins <- seq(min(as.numeric(unlist(df))), max(as.numeric(unlist(df))), length.out = input$bins + 1)
hist(as.numeric(unlist(df)), # histogram
col="gray",
xlim=c(min(as.numeric(unlist(df))), max(as.numeric(unlist(df)))),
border="black",
breaks = seq(min(as.numeric(unlist(df))), max(as.numeric(unlist(df))), length.out = input$bins+1),
prob = TRUE, # show densities instead of frequencies
xlab = input$x,
main = input$titlename)
})
})
})
shinyjs::disable("append")
observeEvent(input$file, {
shinyjs::enable("append")
})
}
shinyApp(ui, server)
Try this
ui <- fluidPage(
useShinyjs(),
navbarPage(title = "Test", id = "tabs",
tabPanel("Home",
sidebarPanel(
fileInput("file", "Upload data",
accept = c(
"text/csv",
"text/comma-separated-values,text/plain",
".csv")
),
checkboxInput("header", "Header", TRUE),
actionButton("append", "Add new tab"),
uiOutput('tabnamesui')
),
mainPanel(
)
)
)
)
server <- function(input, output, session) {
userfile <- reactive({
input$file
})
filereact <- reactive({
read.table(
file = userfile()$datapath,
sep = ',',
header = T,
stringsAsFactors = T
)
})
tabsnames <- reactive({
names(filereact())
})
output$tabnamesui <- renderUI({
req(userfile())
selectInput(
'tabnamesui',
h5('Tab names'),
choices = as.list(tabsnames()),
selected="",multiple = FALSE
)
})
tabnamesinput <- reactive({
input$tabnamesui})
#Append selected tab logic
observeEvent(input$append,{
appendTab(inputId = "tabs",
tabPanel(input$tabnamesui,
sidebarPanel(
actionButton(paste0("remove_", input$tabnamesui), "Delete"),
textInput(paste0("x.",input$tabnamesui), "X-axis label"),
textInput(paste0("titlename",input$tabnamesui), "Title"),
sliderInput("bins", "Number of bins", value = 50, min = 1, max = 100)
),
mainPanel(
plotOutput(paste0("dp2",input$tabnamesui))
)
)
)
})
# Delete selected tab logic
observeEvent(lapply(grep(pattern = "^remove_", x = names(input), value = TRUE), function(x){input[[x]]}),{
if(input$tabs != "Home"){
if (input[[paste0("remove_",input$tabs)]]) { ## remove tab only if delete button has been clicked
removeTab(inputId = "tabs", target = input$tabs)
updateSelectInput(session, "tabnamesui", selected = input$tabnamesui) # keep the selection when re-rendering sidebarPanel
}
}
})
#New tab logic to prevent inserting same tab twice with enable/disable action button
forcecombine = function(idtab,checker) {
colnames(idtab) = colnames(checker)
rbind(idtab,checker)
}
checker<-as.data.frame("checker")
idtab<-as.data.frame("checkers")
#only allow tab entry once
observeEvent(input$append, {
idtab <- paste0(tabnamesinput())
idtab<-as.data.frame(idtab)
checkerx<-forcecombine(idtab,checker)
repeated<-length(grep(idtab,checkerx))
if(repeated==1)
{
shinyjs::disable("append")
}
else {shinyjs::enable("append")
}
})
observeEvent(input$tabnamesui, {
shinyjs::enable("append")
lapply(tabnamesinput(), function(x) {
df <- as.data.table(filereact()[[as.name(tabnamesinput())]])
tab_name <- input$tabnamesui
output[[paste0("dp2",input$tabnamesui)]] <- renderPlot({
bins <- seq(min(as.numeric(unlist(df))), max(as.numeric(unlist(df))), length.out = input$bins + 1)
hist(as.numeric(unlist(df)), # histogram
col="gray",
xlim=c(min(as.numeric(unlist(df))), max(as.numeric(unlist(df)))),
border="black",
breaks = seq(min(as.numeric(unlist(df))), max(as.numeric(unlist(df))), length.out = input$bins+1),
prob = TRUE, # show densities instead of frequencies
xlab = input[[paste0("x.",tab_name)]],
main = input[[paste0("titlename",tab_name)]] )
})
})
})
shinyjs::disable("append")
observeEvent(input$file, {
shinyjs::enable("append")
})
}
shinyApp(ui, server)

R Shiny: Print input from a selectInput function created dynamically from prior inputs

I am struggling to print the output of various selectInput options on my 'Example_2' tab. These fields themselves have been created within the server based on prior inputs from 'Example_1' tab.
Please see below:
library(shinythemes)
library(shiny)
rm(list = ls())
ui <- navbarPage('Example',id = "inTabset",
tabPanel(title = "Example_1", value = "Example_1",
fluidPage(
tags$b( h4("Example_1", align = "left")),
theme = shinytheme("paper"),
fluidRow(
column(6,checkboxGroupInput("checkGroup", label ="",
choices = c(1,2,3,4,5,6,7,8),
selected = c(1,4,7)) )
),
br()
),
hr(),
verbatimTextOutput("example1")
),
tabPanel(title = "Example_2", value = "Example_2",
fluidPage(
tags$b( h4("Example_2", align = "left")),
br(),
fluidRow(
column(4, uiOutput("VarsInput")),
fluidRow(verbatimTextOutput("dataInfo")),
br(),
hr())
)
))
server <- function(input, output, session) {
output$example1 = renderPrint(input$checkGroup)
### output$example2 = ????
### i.e what data (a,b,c,d,e or f) has been chosen from the selectInput below?
K <- reactive({
length(input$checkGroup)
})
output$VarsInput <- renderUI({
NoV = K()
C = sapply(1:(ceiling(NoV)), function(i){paste0(input$checkGroup[i])})
output = tagList()
for(i in seq_along(1:ceiling(NoV))){
output[[i]] = tagList()
output[[i]][[1]] = selectInput(C[i], C[i], c("",c("a","b","c","d","e","f")))
}
output
})
}
shinyApp(ui, server)
In ui I added verbatimTextOutput for your example2.
When dynamically creating outputs, I believe you just need output[[i]] in your for loop.
For name of these selectInput widgets, added "item" instead of just having the id be a number.
Then, you can access the selected values for these inputs through input[[paste0("item", i)]] where i is matched to your checkboxes.
Edit (12/27/20) Based on comment, with varying checkboxes and inputs, you will want to store both the input name (or index) and choice. So, you could make a reactive data frame to store these, instead of just storing the value selected. Also, you need to check if the dynamically created input exists (or is.null) before storing the value. Additionally, when you create your new dynamic inputs, you can check with the index to provide an accurate default/selected value. See if this works for you.
library(shinythemes)
library(shiny)
ui <- navbarPage('Example',id = "inTabset",
tabPanel(title = "Example_1", value = "Example_1",
fluidPage(
tags$b( h4("Example_1", align = "left")),
theme = shinytheme("paper"),
fluidRow(
column(6,checkboxGroupInput("checkGroup", label ="",
choices = c(1,2,3,4,5,6,7,8),
selected = c(1,4,7)) )
),
br()
),
hr(),
verbatimTextOutput("example1")
),
tabPanel(title = "Example_2", value = "Example_2",
fluidPage(
tags$b( h4("Example_2", align = "left")),
br(),
fluidRow(
column(4, uiOutput("VarsInput")),
fluidRow(verbatimTextOutput("dataInfo")),
br(),
hr(),
verbatimTextOutput("example2"))
)
))
server <- function(input, output, session) {
rv <- reactiveValues(df = NULL)
observe({
rv$df <- data.frame(
index = as.numeric(),
choice = as.character()
)
for (i in input$checkGroup) {
the_item <- input[[paste0("item", i)]]
rv$df <- isolate(rbind(rv$df, data.frame(index = i, choice = ifelse(is.null(the_item), "", the_item))))
}
})
output$example1 = renderPrint(input$checkGroup)
output$example2 <- renderPrint(
for (i in input$checkGroup) {
print(input[[paste0("item", i)]])
}
)
K <- reactive({
length(input$checkGroup)
})
output$VarsInput <- renderUI({
NoV = K()
C = sapply(1:(ceiling(NoV)), function(i){paste0(input$checkGroup[i])})
output = tagList()
for(i in seq_along(1:ceiling(NoV))){
output[[i]] = tagList()
output[[i]] = selectInput(paste0("item", C[i]), C[i], c("",c("a","b","c","d","e","f")),
selected = isolate(rv$df$choice[rv$df$index == C[i]]))
}
output
})
}
shinyApp(ui, server)

Resources