通过循环在renderUI中创建值框

时间:2018-09-04 08:29:45

标签: r shiny lapply shinydashboard

我想根据我拥有的数据创建一个值框。 假设我有5个这样的数据变量consumerdata

    id     data    number1   number2
1   k4j       A         67        53
2   rls       B         30        62
3   yv9       C         45        28
4   l6h       D         63        47
5   f08       E         96        75

然后,我需要使用“名称”和“ number1”列创建5个值框。 我没有显示任何数据,也没有错误。

代码

ui <-  dashboardPage(
  dashboardHeader(),
  dashboardSidebar(
    sidebarMenu(
      menuItem("Consumer", tabName = "consumerdata")
    )
  ),  

  dashboardBody(
    tabItems(
      tabItem(tabName = "consumerdata",
              fluidRow(
                tabBox(width = 12,
                       tabPanel("Label",
                                box(width = 12,
                                    uiOutput("consumer")
                                )
                             )
                          ) 
                       )
                    )
                  )
                )
             )

server <- function(input,output) {

    output$consumer <- renderUI({


  lapply(consumerdata$name, function(i) { 

    valueBox(i,
             consumerdata$number1,     #here display number1 one by one like name 
             width = 4
             )
      }) 

    })
}

shinyApp(ui = ui, server = server)

1 个答案:

答案 0 :(得分:0)

您快到这里了,现在您可以遍历一系列数字而不是元素本身,然后将这些数字用作索引。

library(shiny)
library(shinydashboard)

ui <-  dashboardPage(
  dashboardHeader(),
  dashboardSidebar(
    sidebarMenu(
      menuItem("Consumer", tabName = "consumerdata")
    )
  ),  

  dashboardBody(
    tabItems(
      tabItem(tabName = "consumerdata",
              fluidRow(
                tabBox(width = 12,
                       tabPanel("Label",
                                box(width = 12,
                                    uiOutput("consumer")
                                )
                       )
                ) 
              )
      )
    )
  )
)

server <- function(input,output) {

  output$consumer <- renderUI({

    consumerdata <- head(mtcars) #comment this if you already have consumerdata defined

    consumerdata$name <- rownames(consumerdata) #comment this if you already have consumerdata defined

    consumerdata$number1 <- 1:6 #comment this if you already have consumerdata defined


    lapply(1:length(consumerdata$name), function(i) { 


      valueBox(consumerdata$name[i],
               consumerdata$number1[i],     #here display number1 one by one like name 
               width = 4
      )
    } )

  })
}

shinyApp(ui = ui, server = server)