'Return input as list in reactive shiny - dynamic UI in insert UI
I'm using the code from a previous solution R shiny dynamic UI in insertUI
In my app right now, the inputs are rendered by the server and displayed as different elements/rows, like this
$row_1
[1] "LV1" "x1" "x2" "x3"
$row_2
[1] "LV2" "x4" "x5" "x6"
I am actually hoping to get something like this instead:
"LV1" "x1" "x2" "x3"
"LV2" "x4" "x5" "x6"
I tried a few things but I'm unsure as to how to change the handle()
functions to get the output I want.
Screenshots and code:
If you try running the shiny app, you will see this:
Click on + LV
button and then simply select LV1
and then multi-select x1
x2
x3
and so on.
This is how it would look like with the output:
Here's the complete code
library(shiny)
newlist <- as.list(c("LV1", "LV2", "x1", "x2", "x3", "x4", "x5", "x6"))
row_ui <- function(id) {
ns <- NS(id)
fluidRow(
column(2,
uiOutput(ns("ui_placeholder"))),
column(2,
uiOutput(ns("ui_placeholder2"))
)
)
}
row_server <- function(input, output, session) {
return_value <- reactive({c(input$variable1, input$variable2)})
ns <- session$ns
output$ui_placeholder <- renderUI({
selectInput(ns("variable1"), "LV:", choices = c(' ', newlist), selected = NULL)
})
output$ui_placeholder2 <- renderUI({
selectInput(ns("variable2"), "Ind:", choices = c(' ', newlist), selected = NULL, multiple = TRUE)
})
list(return_value = return_value)
}
ui <- fluidPage(
div(id="placeholder"),
actionButton("addLine", "+ LV"),
verbatimTextOutput("out"),
verbatimTextOutput("listout5")
)
server <- function(input, output, session) {
handler <- reactiveVal(list())
observeEvent(input$addLine, {
new_id <- paste("row", input$addLine, sep = "_")
insertUI(
selector = "#placeholder",
where = "beforeBegin",
ui = row_ui(new_id)
)
handler_list <- isolate(handler())
new_handler <- callModule(row_server, new_id)
handler_list <- c(handler_list, new_handler)
names(handler_list)[length(handler_list)] <- new_id
handler(handler_list)
})
output$out <- renderPrint({
lapply(handler(), function(handle) {
handle()
})
})
}
shinyApp(ui, server)
Solution 1:[1]
Try this:
output$out <- renderPrint({
invisible(lapply(handler(), function(handle) {
cat(paste0(paste0(handle(), collapse = " "), "\n"))
}))
})
handle()
returns a list, the first call to paste0
creates one string, the second paste0
adds a new line so that all values from one module are on the same line. invisible
prevents that the return value from lapply
gets printed (only the sideeffect from cat
is printed)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | starja |