当前位置:  开发笔记 > 编程语言 > 正文

根据csv文件的列名创建选择列表,以便在Shiny中进行绘图

如何解决《根据csv文件的列名创建选择列表,以便在Shiny中进行绘图》经验,为你挑选了2个好方法。

我正在尝试构建一个闪亮的应用程序,我可以上传一个csv文件,并根据列名称,填充ui左侧列(滑动条列)上的复选框.根据为y轴选择的列和为x轴选择的列,需要能够使用ggplot创建图表.

我的ui.R看起来像这样:

shinyUI(pageWithSidebar(
  headerPanel("CSV Viewer"),
  sidebarPanel(
    fileInput('file1', 'Choose CSV File',
              accept=c('text/csv', 'text/comma-separated-values,text/plain', '.csv')),
    tags$hr(),
    checkboxInput('header', 'Header', TRUE),
    radioButtons('sep', 'Separator',
                 c(Comma=',',
                   Semicolon=';',
                   Tab='\t'),
                 'Comma'),
    radioButtons('quote', 'Quote',
                 c(None='',
                   'Double Quote'='"',
                   'Single Quote'="'"),
                 'Double Quote'),

   checkboxGroupInput("variable", "Variable:", choices = names(data_set))
  ),
  mainPanel(
    tableOutput('contents')


  )
))

Server.R看起来像这样:

shinyServer(function(input, output) {
  output$contents <- renderTable({

    # input$file1 will be NULL initially. After the user selects and uploads a 
    # file, it will be a data frame with 'name', 'size', 'type', and 'datapath' 
    # columns. The 'datapath' column will contain the local filenames where the 
    # data can be found.

    inFile <- input$file1

    if (is.null(inFile))
      return(NULL)

    data_set<-read.csv(inFile$datapath, header=input$header, sep=input$sep, quote=input$quote)
  })

  output$choose_dataset <- renderUI({
    selectInput("dataset", "Data set", as.list(data_sets))
  })

  # Check boxes
  output$choose_columns <- renderUI({
    # If missing input, return to avoid error later in function
    if(is.null(input$dataset))
      return()

    # Get the data set with the appropriate name

    colnames <- names(contents)

    # Create the checkboxes and select them all by default
    checkboxGroupInput("columns", "Choose columns", 
                       choices  = colnames,
                       selected = colnames)
  })

})

我无法在滑块栏的数据集中加载列名?任何指针我怎么能这样做.我正在加载一个csv文件,一旦加载了文件,我需要能够加载用我的数据集的列名填充滑块.

更新编辑:

添加了来自OP的请求(请参阅已接受答案中的注释)以读取csv并选择用于绘图的轴ggplot.另外还为此添加了答案.



1> Mike Wise..:

这个答案只是修复了csv加载问题,请参阅下面的下一个答案,其中一个实际上是用ggplot进行绘图.

所以(在合并到一个文件中以便更容易处理之后),我添加了一个checkboxGroupInput到ui部分和一个对应updateCheckboxGroupInput的服务器部分.当数据集发生变化时,我需要它来更新组,所以我重新组织了一些代码,使data_set加载部分reactive封装在updateCheckboxGroupInput内部observer.

所以这就是你想要的:

library(shiny)
library(shinydashboard)
library(leaflet)
library(data.table)

ui <- pageWithSidebar(
  headerPanel("CSV Viewer"),
  sidebarPanel(
    fileInput('file1', 'Choose CSV File',
              accept=c('text/csv', 'text/comma-separated-values,text/plain', '.csv')),
    tags$hr(),
    checkboxInput('header', 'Header', TRUE),
    checkboxGroupInput("inCheckboxGroup",
                       "Checkbox group input:",
                       c("label 1" = "option1",
                         "label 2" = "option2")),
    radioButtons('sep', 'Separator',
                 c(Comma=',',
                   Semicolon=';',
                   Tab='\t'),
                 ','),
    radioButtons('quote', 'Quote',
                 c(None='',
                   'Double Quote'='"',
                   'Single Quote'="'"),
                 '"'),
    uiOutput("choose_columns")
  ),
  mainPanel(
    tableOutput('contents')
  )
)

server <- function(input, output,session) {
  dsnames <- c()

  data_set <- reactive({
    req(input$file1)
    inFile <- input$file1
    data_set<-read.csv(inFile$datapath, header=input$header, 
                       sep=input$sep, quote=input$quote)
  })
  output$contents <- renderTable({
    data_set()
  })
  observe({
    req(input$file1)
    dsnames <- names(data_set())
    cb_options <- list()
    cb_options[ dsnames] <- dsnames
    updateCheckboxGroupInput(session, "inCheckboxGroup",
                             label = "Check Box Group",
                             choices = cb_options,
                             selected = "")
  })

  output$choose_dataset <- renderUI({
    selectInput("dataset", "Data set", as.list(data_sets))
  })

  # Check boxes
  output$choose_columns <- renderUI({
    # If missing input, return to avoid error later in function
    if(is.null(input$dataset))
      return()

    # Get the data set with the appropriate name

    colnames <- names(contents)

    # Create the checkboxes and select them all by default
    checkboxGroupInput("columns", "Choose columns", 
                       choices  = colnames,
                       selected = colnames)
  })
}
shinyApp(ui, server)

这是一个截图:

在此输入图像描述



2> Mike Wise..:

因此添加另一个答案以容纳一个额外的请求 - 它不仅读取文件,而且允许您选择用于绘图的列,它实际上在单独的选项卡中绘制ggplot2:

library(shiny)
library(shinydashboard)
library(leaflet)
library(data.table)
library(ggplot2)

ui <- pageWithSidebar(
  headerPanel("CSV Viewer"),
  sidebarPanel(
    fileInput('file1', 'Choose CSV File',
              accept=c('text/csv','text/comma-separated-values,text/plain','.csv')),
    tags$hr(),
    checkboxInput('header', 'Header', TRUE),
    fluidRow(
      column(6,radioButtons("xaxisGrp","X-Axis:", c("1"="1","2"="2"))),
      column(6,checkboxGroupInput("yaxisGrp","Y-axis:", c("1"="1","2"="2")))
    ),
    radioButtons('sep', 'Separator',
                 c(Comma=',', Semicolon=';',Tab='\t'), ','),
    radioButtons('quote', 'Quote',
                 c(None='','Double Quote'='"','Single Quote'="'"),'"'),
    uiOutput("choose_columns")
  ),
  mainPanel(
    tabsetPanel(
      tabPanel("Plot",plotOutput("plot")),
      tabPanel("Data", tableOutput('contents'))
    )
  )
)
server <- function(input, output,session) {
  dsnames <- c()

  data_set <- reactive({
    inFile <- input$file1

    if (is.null(inFile))
      return(mtcars)

    data_set<-read.csv(inFile$datapath, header=input$header, 
                       sep=input$sep, quote=input$quote)
  })

  output$contents <- renderTable({data_set()})

  observe({
    dsnames <- names(data_set())
    cb_options <- list()
    cb_options[ dsnames] <- dsnames
    updateRadioButtons(session, "xaxisGrp",
                             label = "X-Axis",
                             choices = cb_options,
                             selected = "")
    updateCheckboxGroupInput(session, "yaxisGrp",
                             label = "Y-Axis",
                             choices = cb_options,
                             selected = "")
  })
  output$choose_dataset <- renderUI({
    selectInput("dataset", "Data set", as.list(data_sets))
  })
  output$plot = renderPlot(
    {
      df <- data_set()
      gp <- NULL
      if (!is.null(df)){
        xv <- input$xaxisGrp
        yv <- input$yaxisGrp
        if (!is.null(xv) & !is.null(yv)){
          if (sum(xv %in% names(df))>0){ # supress error when changing files
            mdf <- melt(df,id.vars=xv,measure.vars=yv)
            gp <- ggplot(data=mdf) + 
               geom_point(aes_string(x=xv,y="value",color="variable"))
          }
        }
      }
      return(gp)
    }
  )
  output$choose_columns <- renderUI({

    if(is.null(input$dataset))
      return()
    colnames <- names(contents)
    checkboxGroupInput("columns", "Choose columns", 
                       choices  = colnames,
                       selected = colnames)
  }) 
}
shinyApp(ui, server)

产量: 在此输入图像描述

推荐阅读
ifx0448363
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有