Clara Potin
Clara Potin

Reputation: 13

UI function in Shiny R

I need to add some Inputs in function of other inputs in Shiny, I don't know how to do it, I've done a renderUI and then a uiOutput but i doesn't function... I add the code:


inputs = function(dades1){
  for (i in 1:ncol(dades1)) {
      if (dades1[i]=="Edad") {
      
      insertUI(     
        selector = "$Edad",
        where = "afterEnd",
        multiple = TRUE, immediate = TRUE,
        ui = radioButtons( inputId = "sel1", 
                           choices = c("1","0"), 
                           selected = c(1,0)))
    }
    
    else if (dades1[i]=="Gender") {
      insertUI(     
        selector = "$Gender",
        where = "afterEnd",                 multiple = TRUE, immediate = TRUE,
        ui = 
          radioButtons( inputId = "sel2", 
                        choices = c("1","0"), 
                        selected = c(1,0)))}}}

(I've shorten the function but there are more 'else ifs') Then once done the function I add to the server:

output$cc<-renderUI({
          dades1<-select(cov,input$vars)
          dades1<-cbind(UCI,dades1)
          inputs(dades1)
        })

And finally to the ui:

uiOutput("cc"),

Upvotes: 1

Views: 82

Answers (1)

jpdugo17
jpdugo17

Reputation: 7116

  1. insertUI is usually is called inside an observer. There is no need to call it inside a reactive.
  2. radioButtons is missing arguments and selected should be length one.

I made an example app that calls a function that inserts the ui when a button is pressed.

library(shiny)
library(purrr)

inputs <- function(dades1) {
    
    #same as for (i in 1:ncol(dades1)) {...}
    walk(1:ncol(dades1), ~{
        
        #.x instead of i
        if (names(dades1[.x]) == 'Species') {
            
            insertUI(     
                selector = "#add",
                where = "afterEnd",
                multiple = TRUE, immediate = TRUE,
                ui = radioButtons( inputId = "sel1",
                                   label = 'New Input',
                                   choices = c("1","0"), 
                                   selected = 1))
        }
        
    })
    
}


ui <- fluidPage(
  actionButton('add', 'Add Input')
)

server <- function(input, output, session) {
  
    observeEvent(input$add, {
        
        inputs(iris)
    
    })    
    
}

shinyApp(ui, server)

Upvotes: 1

Related Questions