r - 如何在 Shiny 中读取 csv 文件?

标签 r file-upload shiny shiny-reactivity

我正在尝试创建一个 Shiny 的仪表板,允许用户选择 csv 文件。该文件仅包含两列:订单号和创建日期。我希望用户能够另外选择他们想要的日期范围并获得摘要计数统计数据。

到目前为止我的代码如下:

library(shiny)
library(plotly)
library(colourpicker)
library(ggplot2)


ui <- fluidPage(
  titlePanel("Case Referrals"),
  sidebarLayout(
    sidebarPanel(
      fileInput("file", "Select a file"),
      sliderInput("period", "Time period observed:",
                  min(data()[, c('dateCreated')]), max(data()[, c('dateCreated')]),
                  value = c(min(data[, c('dateCreated')]),max(data()[, c('dateCreated')])))
    ),
    mainPanel(
      DT::dataTableOutput("table")
    )
  )
)

# Define the server logic
server <- function(input, output) {
  
  # file input
  input_file <- reactive({
    if (is.null(input$file)) {
      return("")
    }
  })
  
  
  # summarizing data into counts
  data <- input_file()
  data <- subset(data, dateCreated >= input$period[1] & dateCreated <= input$period[2])


  output$table <- DT::renderDataTable({
    data
  })
  
  
  
}

shinyApp(ui = ui, server = server)

我收到一条错误消息:

data()[, c("dateCreated")] 中的错误:维度数不正确

任何人都可以帮助我了解问题可能是什么和/或提供更好的框架来执行此操作吗?为了清楚起见,在 csv 文件中,createDate 变量被分解为下订单时的各个日期。

谢谢!

最佳答案

我为错误步骤添加了注释。

library(shiny)


ui <- fluidPage(
  titlePanel("Case Referrals"),
  sidebarLayout(
    sidebarPanel(
      fileInput("file", "Select a file"),
      
      # you cannot call data() in your ui. 
      # You would have to wrap this in renderUI inside of your server and use
      # uiOutput here in the ui
      sliderInput("period", "Time period observed:", min = 1, max = 10, value = 5)
    ),
    mainPanel(
      DT::dataTableOutput("table")
    )
  )
)

# Define the server logic
server <- function(input, output) {

  input_file <- reactive({
    if (is.null(input$file)) {
      return("")
    }

    # actually read the file
    read.csv(file = input$file$datapath)
  })

  output$table <- DT::renderDataTable({

    # render only if there is data available
    req(input_file())

    # reactives are only callable inside an reactive context like render
    data <- input_file()
    data <- subset(data, dateCreated >= input$period[1] & dateCreated <= input$period[2])

    data
  })



}

shinyApp(ui = ui, server = server)

关于r - 如何在 Shiny 中读取 csv 文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70161413/

相关文章:

html - 使用 HTML 或 CSS 居中对齐 Shiny box header

php file_exists 返回 false 即使我的 linux 上存在文件

Safari 中的 HTML5 文件 API 大小问题

R : Load only once a . 部署的 ShinyApp 中的 RData

r - R中预测和预测函数的区别

jquery - 如何在 bootstrap-fileinput 插件中显示进度?

javascript - 如何创建自定义 JS 函数以将 plotly 图像复制到 R shiny 中的剪贴板

r - 在 R 中绘制棋盘

python - 从Python中的Requests模块读取文件

r - data.table 有效替代分组分配为 DT[,x :=f(y), by=z]?