【问题标题】:Producing the same output multiple times多次产生相同的输出
【发布时间】:2020-04-25 17:45:11
【问题描述】:

这显然是一个最小的示例,但是对于较重的代码,当我必须有效地写出三个相同的输出但每个输出都经过过滤以表示三个选项卡名称时,它可能是及时的并且会使我的代码混乱。

有没有更有效的方法来产生这个结果,我不必写出三个单独的renderTable 语句?

df <- structure(list(id = c("Tony","Tony","Tony","Tony","Tony","Alex","Alex","Alex","Alex","Alex","Jen","Jen","Jen","Jen","Jen"), 
                     sales = c(13L, 17L, 20L, 30L, 38L, 24L, 10L, 1L, 14L, 43L, 21L, 6L, 14L, 17L, 12L), 
                     leads = c(63L, 91L, 51L, 81L, 88L, 97L, 77L, 61L, 74L, 87L, 74L, 68L, 56L, 53L, 63L)), 
                row.names = c(NA, -15L), class = "data.frame")

ui <- fluidPage(navlistPanel("Test",
                  tabPanel("Tony",
                           tableOutput("t1")),
                  tabPanel("Alex",
                           tableOutput("t2")),
                  tabPanel("Jen",
                           tableOutput("t3"))))

server <- function(input,output,session){
output$t1 <- renderTable({df%>%filter(id=='Tony')})
output$t2 <- renderTable({df%>%filter(id=='Alex')})
output$t3 <- renderTable({df%>%filter(id=='Jen')})
}

shinyApp(ui,server)

【问题讨论】:

    标签: r shiny shinydashboard shiny-server shiny-reactivity


    【解决方案1】:

    你可以使用 sapply:

    df <- structure(list(id = c("Tony","Tony","Tony","Tony","Tony","Alex","Alex","Alex","Alex","Alex","Jen","Jen","Jen","Jen","Jen"),
                         sales = c(13L, 17L, 20L, 30L, 38L, 24L, 10L, 1L, 14L, 43L, 21L, 6L, 14L, 17L, 12L),
                         leads = c(63L, 91L, 51L, 81L, 88L, 97L, 77L, 61L, 74L, 87L, 74L, 68L, 56L, 53L, 63L)),
                    row.names = c(NA, -15L), class = "data.frame")
    
    ui <- fluidPage(navlistPanel("Test",
                                 tabPanel("Tony",
                                          tableOutput("t1")),
                                 tabPanel("Alex",
                                          tableOutput("t2")),
                                 tabPanel("Jen",
                                          tableOutput("t3"))))
    library(dplyr)
    server <- function(input,output,session){
      names <- c("Tony", "Alex", "Jen")
      sapply(1:length(names), function(k) {
        output[[paste0("t", k)]] <- renderTable({df%>%filter(id==names[k])})
      })
    }
    
    shinyApp(ui,server)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-07
      • 1970-01-01
      • 1970-01-01
      • 2015-04-22
      • 2021-07-16
      相关资源
      最近更新 更多