Is is possible to build UI objects using for loops in the shiny ui.R?

5,047 views
Skip to first unread message

claymore...@gmail.com

unread,
Apr 25, 2014, 5:09:37 PM4/25/14
to shiny-...@googlegroups.com
For example, consider this modification of the base example shiny code which currently does not work

shinyUI(fluidPage(

  # Application title
  titlePanel("Old Faithful Geyser Data"),

  # Sidebar with a slider input for number of bins
  sidebarLayout(
    sidebarPanel(
      for (i in 1:5) {
      sliderInput(paste0("bin", i),
                  paste0("Bin Number ", i),
                  min = 1,
                  max = 50,
                  value = 30),}
      
      sliderInput(paste0("bin", 6),
                  paste0("Bin Number ", 6),
                  min = 1,
                  max = 50,
                  value = 30)
    ),

    # Show a plot of the generated distribution
    mainPanel(
      plotOutput("distPlot")
    )
  )
))

Is this kind of code possible in ui.R with some sort of bracketing syntax?  I might like to have say 20-40 selectInput options available on the sidebarLayout.

Herman Sontrop

unread,
Apr 25, 2014, 8:14:27 PM4/25/14
to shiny-...@googlegroups.com
Hi,

this is very well possible. Let's say you want to construct a set of 10 radio button inputs in an automatic way. For this you can use renderUI, uiOutput and reactiveValuesToList :
Furthermore, it is useful to realize renderUI can take a list as well.

In server.r you would have something like this:

output$Dynamic <- renderUI({
      L <- vector("list",10)       
      for(i in 1:10){
            LL[[i]] <- list(radioButtons(inputId = paste0("mVariable",i), label = paste0("mVariable",i), choices = c("A","B","C")))
      }                              
})

in ui.R you call:

uiOutput("Dynamic")

in turn, in server.r you can retrieve the values for the generated inputs by:

isolate(unlist(reactiveValuesToList(input)[paste0("mVariable",1:10)]))

the isolate function is used to prevent taken a dependency on all input elements, which can make your app very slow

hope this helps!

kind regards, Herman


Herman Sontrop

unread,
Apr 25, 2014, 9:14:09 PM4/25/14
to shiny-...@googlegroups.com
oops, a slight error -  the output$Dynamic code should read:

output$Dynamic <- renderUI({
      LL <- vector("list",10)       
      for(i in 1:10){
            LL[[i]] <- list(radioButtons(inputId = paste0("mVariable",i), label = paste0("mVariable",i), choices = c("A","B","C")))
      }      
      return(LL)                     
})



Op zaterdag 26 april 2014 02:14:27 UTC+2 schreef Herman Sontrop:

Andrés Felipe Flórez Rivera

unread,
Apr 25, 2014, 10:54:51 PM4/25/14
to shiny-...@googlegroups.com
Thanks Hernan for help me. I get do it:
server.R is:

shinyServer(function(input,output){
     observe({
      if (input$test == 0) 
        return()
      isolate({
          output$value <-renderTable({
                     matrix_input <- list()
                              for(j in 1:(input$obs+1)){matrix_input[j] <- paste0("<input id='element",j,"_", 1:1,
                                                           "' class='shiny-bound-input span7' type='number' value=''>")}
                              matrix <- data.frame(matrix_input) 
                              colnames(matrix)<- c("Size n",sapply(1:input$obs,function(z)paste("Cat",z)))
 matrix}, sanitize.text.function = function(x) x)
      })
    })
output$summary <- renderPrint({summary("'element$value")})
  })


and the ui.R is:

shinyUI(pageWithSidebar(
  headerPanel(title ="Elicitación de Expertos"),
  sidebarPanel(
     tags$head(
        tags$style(type="text/css", "select { width: 100px; }"),
        tags$style(type="text/css", "textarea { max-width: 185px; }"),
        tags$style(type="text/css", ".jslider { max-width: 200px; }"),
        tags$style(type='text/css', ".well { max-width: 470px; }"),
        tags$style(type='text/css', ".span4 { max-width: 830px; }")
      ), 
    numericInput("obs", "Número de Categorías:", 2, min =2, max =10),
h3(actionButton("test","Crear")),
    conditionalPanel(condition = "input.density == true",sliderInput(inputId = "bw_adjust", label = "Bandwidth Adjustment",
                     min = 0.2, max = 2, value = 1, step = 0.2))
  ),
  mainPanel(
    tabsetPanel(
      tabPanel("Plot", tableOutput("value")),
      tabPanel("Summary",verbatimTextOutput(outputId = "summary"))
    ))
)
)

the question now is how I can to extract each value of  numericInput(), that in this case have a id='element, for example, like this  "x<-input$cat1"


thanks again!

claymore...@gmail.com

unread,
Apr 28, 2014, 12:37:44 PM4/28/14
to shiny-...@googlegroups.com
Hi Herman,

Thanks very much for this guidance - it answers what I'm looking for.  Thanks for adding the related extra tip with isolate too.

Herman Sontrop

unread,
Apr 28, 2014, 3:01:47 PM4/28/14
to shiny-...@googlegroups.com
great to hear! If you have more questions just ask...

Op maandag 28 april 2014 18:37:44 UTC+2 schreef claymore...@gmail.com:

konrad...@gmail.com

unread,
Apr 30, 2014, 4:49:07 PM4/30/14
to shiny-...@googlegroups.com
Hi!

I tried to use "isolate(unlist(reactiveValuesToList(input)[paste0("rep",1:10)]))"

To get the values back and try to call some functions, but the functions (pasted above) returns only NULL.

I accumulate a list of variables in a function:

    output$generateImages <- renderUI({

Like this:

variable "i" is incremented each loop taking values 1,2,3,4,5,6,7....
        txt<-paste0("rep",i)
        pp<-paste0(path,"/",dir,"/",thisRepresentative)
        #print(txt)
        LL[[i]] <- list(actionButton(txt,icon=imageOutput(pp,width="100px",height="100px"),label=dir))

And there are two problems:

1) The image is not appearing.
2) when I use the "browse()" function to check out what "isolate(unlist(reactiveValuesToList(input)[paste0("rep",1:10)]))" gives, it gives NULL.

How can I access each button ? When not using a list, I was able to do it by just writing "input$rep1". I tried various options now, like input$LL[[2]]>0 etc, but without success :(. Is there any good tutorial on this?

bhaven mehta

unread,
Jan 7, 2018, 10:32:09 PM1/7/18
to Shiny - Web Framework for R
Hi Herman, 

   I am using the script you have mentioned. it is working for a single image. Giving the following output.

When I try to do for two plots, I get the following.


What I want  is as follows:




Could you help me with this?


My R code is attached here.


Thanks,

Bhaven.

server.R
ui.R
Reply all
Reply to author
Forward
0 new messages