闪亮允许用户选择数据(存储)及其列?

时间:2017-12-21 22:52:24

标签: r shiny

我想允许用户从列表中选择数据,例如:mtcars,iris,USArrests。然后根据用户的选择,他可以选择所选数据的列。以下代码仅允许选择mtcars colums

library(shiny)

vchoices <- 1:ncol(mtcars)
names(vchoices) <- names(mtcars)

runApp(list(
ui = basicPage(
h2('The mtcars data'),
checkboxGroupInput("columns","Select Columns",choices=vchoices,inline=T),
dataTableOutput('mytable')
),
server = function(input, output) {

observeEvent(input$columns,{
  cols <- as.numeric(input$columns)
  if(length(input$columns) == 1){
    df <- data.frame(mtcars[,cols])
    names(df) <- names(mtcars)[cols]
    output$mytable = renderDataTable(df)

  }else{
    output$mytable = renderDataTable(mtcars[,cols])
  }
 })
}
))

修改代码的任何建议,旨在允许用户从数据框列表中选择(mtcars,iris,USArrest)?

1 个答案:

答案 0 :(得分:0)

修改

这是一个带复选框的选项 - 这与原始答案更相似。

library(shiny)
library(DT)

runApp(list(
    ui = fluidPage(
        h2("Pick Columns from Various Dataframes"),
        sidebarLayout(
            sidebarPanel(
                selectInput("dataset", "Dataset", c("mtcars", "iris", "USArrests")),
                uiOutput("listCols")
            ),
            mainPanel(
                dataTableOutput('myTable')
                )
        )
    ),
    server = function(input, output) {
        datasetInput <- reactive({
            switch(input$dataset,
                   "mtcars" = mtcars,
                   "iris" = iris, 
                   "USArrests" = USArrests)
        })

        output$listCols <- renderUI({
            checkboxGroupInput("listCols", "Columns to show:",
                               choices = names(datasetInput()), 
                               selected = names(datasetInput()))
            })

        output$myTable <- DT::renderDataTable({
            validate(
                need(!is.null(input$listCols), "Please select at least one column"),
                need(input$listCols %in% names(datasetInput()), "")
                )
            datatable(
                datasetInput()[, input$listCols, drop = FALSE], rownames = FALSE
            )
        })
    }
)
)

原始答案

用户可以使用selectInput选择数据框。然后,DT extension colvis可用于显示/隐藏列。

以下是一个例子:

library(shiny)
library(DT)

runApp(list(
    ui = basicPage(
        h2("Pick Columns from Various Dataframes"),
        selectInput("dataset", "Dataset", c("mtcars", "iris", "USArrests")),
        dataTableOutput('myTable')
    ),
    server = function(input, output) {
        datasetInput <- reactive({
            switch(input$dataset,
                   "mtcars" = mtcars,
                   "iris" = iris, 
                   "USArrests" = USArrests)
        })
        output$myTable <- DT::renderDataTable(
            datatable(
                datasetInput(), rownames = FALSE,
                extensions = 'Buttons', options = list(dom = 'Bfrtip', buttons = I('colvis'))
            )
        )
    }
)
)