首页 > 解决方案 > 在 Shiny 中为输出创建函数

问题描述

我对 Shiny 应用程序中的输出函数有疑问。是否可以编写一个以变量为名称的输出函数以多次使用它?

例如一个简短的摘录:

  output$MainBody <- renderUI({
    fluidPage(
      gradientBox(
        title = "Test",
      )
    )
  })

是否可以使用这样的功能:

dt_representation <- function(x){
      output$x <- renderUI({
        fluidPage(
          gradientBox(
            title = "Test",
          )
        )
      })
}

并调用这个函数:

dt_representation(MainBody)

这是一种可能性,还是在 Shiny 中不起作用?

标签: rfunctionshinyshinydashboard

解决方案


强烈建议使用Pork Chop所说的模块。
但它可能会在我使用这样一个小“黑客”的时候发生:

library(shiny)

ui <- fluidPage(
   uiOutput("all_id")
)

server <- function(input, output) {

    # Define function
    createUI <- function(x, text) {
        output[[x]] <<- renderUI({
            div(text)
        })
    }

    # Use function
    createUI("id1", "Here is my first UI")
    createUI("id2", "Here is my second UI")

    # Combine all in one
    output$all_id <- renderUI({
        do.call(fluidRow, lapply(c("id1","id2"), uiOutput))
    })
}

shinyApp(ui = ui, server = server)

推荐阅读