Advanced topics2 – Create re-usable UI elements
http://zevross.com/blog/2016/04/19/r-powered-web-applications-with-shiny-a-tutorial-and-cheat-sheet-with-40-example-apps/ Posted on by [email protected]
Create re-useable UI elements
여러 tab에 같은 UI element를 넣어야할때, (10개의 tab에 변수선택을 위한 같은 selectbox를 구현하고 싶을때)
같은 코드를 여러번 copy&paste한다면 각각 ID도 따로 생성해야 하고 수정에 대한 관리도 어려워 질것이다.
=> 필요한 UI element를 output하는 function 을 만들고, 간단히 call하면 된다.
(물론 modules을 사용할수도 있겠지만)
renderUI
in server , htmlOutput
(uiOutput) in ui
renderUI 예제
https://shiny.rstudio.com/reference/shiny/0.14/renderUI.html (Rendering functions)
기본
server <- function(input, output, session) { output$moreControls <- renderUI({ tagList( sliderInput("n", "N", 1, 1000, 500), textInput("label", "Label") ) }) } ui <- basicPage( #uiOutput("moreControls") htmlOutput("moreControls") ) shinyApp(ui, server)
함수
server <- function(input, output, session) { button_Action <- function(){ output$moreControls <- renderUI({ tagList( sliderInput("n", "N", 1, 1000, 500), textInput("label", "Label") ) }) } observeEvent(input$btn_action, { button_Action() }) } ui <- basicPage( actionButton("btn_action", "Button"), htmlOutput("moreControls") ) shinyApp(ui, server)
do.call
server <- function(input, output, session) { button_Action <- function(){ output$moreControls <- renderUI({ output_list <- lapply(c(1:3), function(x){ tagList( sliderInput(paste0("n",x), paste0("N",x), 1, 1000, 500), textInput(paste0("label",x), paste0("LABEL",x)) ) }) do.call(tagList, output_list) }) } observeEvent(input$btn_action, { button_Action() }) } ui <- basicPage( actionButton("btn_action", "Button"), htmlOutput("moreControls") ) shinyApp(ui, server)
renderUI 예제2 : Create re-usable UI elements
ex) title, select box, radio button, check box를 생성하는 function(아래예 createSelectRadio() ) 을 생성하고,
각 tab에서 해당 function을 3번 call하면, components의 list를 output한다. App 28
server <- function(input, output, session) { # A function to create a block of UI elements createSelectRadio <- function(id, title){ selectID <- paste0("myselect", id) radioID <- paste0("myradio", id) checkID <- paste0("mycheck", id) res <- list( h2(title), selectInput( inputId = selectID, label="", choices = sample(LETTERS,3)), radioButtons( inputId = radioID, label="", choices = sample(letters,3)), checkboxInput(inputId = checkID, label="", value=TRUE) ) return(res) } # here we create our blocks of UI elements by running the function output$forPlot <- renderUI({createSelectRadio(1, "In plot tab")}) output$forSummary <- renderUI({createSelectRadio(2, "In summary tab")}) output$forTable <- renderUI({createSelectRadio(3, "In table tab")}) } ui <- basicPage( h3("All tabs have the same set of components created with a function."), tabsetPanel( tabPanel("Summary", uiOutput("forSummary")), tabPanel("Plot", uiOutput("forPlot")), tabPanel("Table", uiOutput("forTable")) ) ) shinyApp(ui, server)