在Shiny R中上传文件之前显示数据

时间:2015-03-23 21:57:16

标签: r file-upload shiny

我创建了一个简单的Shiny应用程序,允许用户上传csv文件并使用上传的数据绘制各种图表。我希望将一些数据预先加载到应用程序中,这样没有任何数据的用户仍可以绘制图形。

现在我只是想打印上传文件或样本数据的表格。

我写了以下不起作用的代码:

server.R

 library(shiny)
 library(ggplot2)

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

    inFile <- input$file1

    if (!is.null(inFile)){
      renderTable({
        read.csv(inFile$datapath, header=input$header, sep=input$sep, 
             quote=input$quote)})
    }
    else{
      renderDataTable({
          diamonds[, input$show_vars, drop = FALSE]})
    }
   })
 })

ui.R

library(shiny)

shinyUI(fluidPage(
  titlePanel("Test"),
   sidebarLayout(
    sidebarPanel(
      fileInput('file1', 'Choose CSV File',
                accept = c(
                  '.csv',
                  '.tsv'
                 )
       ),
       tags$hr(),
       checkboxInput('header', 'Header', TRUE),
       radioButtons('sep', 'Separator',
                   c(Comma=',',
                     Semicolon=';',
                     Tab='\t'),
                     ','),
       radioButtons('quote', 'Quote',
                   c(None='',
                     'Double Quote'='"',
                     'Single Quote'="'"),
                    '"')
     ),
    mainPanel(
              tabsetPanel(type = "tabs", 
                  tabPanel("Table", tableOutput("contents"))
              )
             )
   )
))

我猜测我没有正确分配输出$内容,但我真的不知道如何修复它。

1 个答案:

答案 0 :(得分:2)

您无法从renderTable内拨打renderDataTablereactive()。因此将它改为:

 shinyServer(function(input, output) {
   tableData <- reactive({

     inFile <- input$file1

     if (!is.null(inFile)){
       read.csv(inFile$datapath, header=input$header, sep=input$sep, 
               quote=input$quote)
     }
     else {
       diamonds[, input$show_vars, drop = FALSE]
     }
   })

   output$contents <- renderTable({
     tableData()
   })
 })
相关问题