如何从按日期排序的基于目录的数据库导出.csv?

时间:2016-03-17 16:34:29

标签: r database export shiny

第一次闪亮的用户,我想我已经完成了大部分设置。代码我从基于目录的数据库中检索某些数据。输出是一个csv文件,我希望能够直接从闪亮下载。

下面的代码是非常基本的:

  1. 需要inputed日期并分隔D / M / Y并创建搜索字词
  2. 还会创建表示不同文件的某些关键字以进行搜索
  3. 搜索特定文件夹并检索CSV。文件
  4. 然后,它仅检索标记为此文件中的inputs之一的数据
  5. 此数据应通过CSV或XLS格式的Shiny应用程序下载/ ouptuted
  6. 我的输入是:

    inputId = "NaVDate" =这是日期(用于搜索和检索.csv)

    inputId = "FundID" =这是在步骤4中对数据进行排序的ID

    输出是:

    Forwards_Fund
    

    这些已经包含在下面的代码中:

    UI.R

    library(shiny)
    
    
    ui <- fluidPage(
    
      # Date input by user
      dateInput(inputId = "NaVDate", label = "Select NaV Date", 
                format = "yyyy-mm-dd", startview = "month", weekstart = 0),
      # 
      textInput(inputId = "FundID", label = "Enter Fund ID (Numeric Only)", value = "", width = NULL, placeholder = NULL),
    
       downloadButton("downloadData", "Download")
    
    
    )
    

    SERVER.R

    server <- function(input, output) {
    
      # extract inputed month / year / day and vectorize ( inputed in YYYY-MM-DD format)
    
    
      timestrip   <- reactive({unlist(strsplit(as.character(input$NaVDate), split = ""))}) 
    
    
      year   <- paste(timestrip[1], timestrip[2], timestrip[3], timestrip[4], sep = "")
      month  <- paste(timestrip[6], timestrip[7], sep = "")
      day    <- paste(timestrip[9], timestrip[10], sep = "")
    
      Date      = paste(year, month, day, sep = "")
    
    
      # create directory search criteria for the required files - eg.("XCP4P487FOFFET_20160315.CSV")
    
      Forwards  = paste0("*FOFFET_", Date, ".CSV$")
    
    
      # create main directory file path
    
      file_path <- paste0("C:/Users/dell Optiplex/Desktop/Equilibrium Weekly Macro/", year,"/", month) 
    
    
      # Search through file_path for criteria and create individual .csv filepath
    
      Forwards_CSV_path  = list.files(file_path, 
                                      pattern = Forwards, full.names=TRUE, 
                                      ignore.case=TRUE)
    
    
      # Read Data from CSV files
    
      Forwards_data = do.call(rbind, lapply(Forwards_CSV_path, function(x) read.csv(x, sep = ";", stringsAsFactors = FALSE)))
    
    
      # Extract data from the inputed fund code (input$FundID) 
    
      Forwards_Fund  <- reactive({
        Forwards_data[which(Forwards_data$Fund.Code == input$FundID),]
      })
    
      ## download above data from shiny app
    
    output$downloadData <- downloadHandler(
        filename = function() {
          paste('data-', Sys.Date(), '.csv', sep='')
        },
        content = function(con) {
          write.csv(Forwards_Fund(), con)
        }
      )
    
    
    }
    
    shinyApp(server = server, ui = ui)
    

    错误

    Listening on http://127.0.0.1:6132
    Warning: Error in [: object of type 'closure' is not subsettable
    Stack trace (innermost first):
        44: paste
        43: server [#9]
         4: <Anonymous>
         3: do.call
         2: print.shiny.appobj
         1: print
    Error in timestrip[1] : object of type 'closure' is not subsettable
    

    编辑: - 更新

    这是一个闪亮的应用程序,它从基于目录的数据库中检索CSV文件的名称。我将继续使用下载按钮升级它。

    我的桌面上有一个名为EquilibriumWeeklyMacro的文件

    C:/Users/dell Optiplex/Desktop/EquilibriumWeeklyMacro/
    

    它包含多个按日期排序的文件

    C:/Users/dell Optiplex/Desktop/EquilibriumWeeklyMacro/2016/03/
    

    在那里我有一个名为

    的CSV文件
    XCP4P487FOFFET_20160315.CSV
    

    请注意FOFFET_20160315结尾

    如果我在Shiny应用程序框中输入XCP4P487FOFFET_20160315.CSV,以下Shiny应用程序应该能够从该文件中检索2016-03-15

    除了最后一部分之外,下面的代码是有效的:

    output$ForwardText  =  renderText({list.files(as.character(FileDirectory()), 
                                                         pattern = as.character(ForwardSearchString()), full.names=TRUE, 
                                                         ignore.case=TRUE)
                                                          })
    

    我知道问题出在上面。 以下是该应用的代码:

    library(shiny)
    
    
    # XCP4P487FOFFET_20160315.CSV
    # C:/Users/dell Optiplex/Desktop/EquilibriumWeeklyMacro/2016/03/
    
    ui <- fluidPage(
    
      # Date input by user
    
      dateInput(inputId = "NaVDate", label = "Select NaV Date",
                format = "yyyy-mm-dd", startview = "month", weekstart = 0),
    
      textOutput("ForwardText")
    
    )
    
    
    
      server <- function(input, output) {
    
    
    
        DateInput <-       reactive({format(as.Date(input$NaVDate), "%Y%m%d")})
    
    
        FileDirectory <- reactive({paste("C:/Users/dell Optiplex/Desktop/EquilibriumWeeklyMacro/",
                                         substr(as.character(DateInput()), 1, 4), "/",
                                         substr(as.character(DateInput()), 5, 6),"/", sep = "") 
                                          })
        # Search String 
    
        ForwardSearchString <- reactive({paste("FOFFET_", as.character(DateInput()), ".CSV")})
    
        # Search through file_path for criteria and create individual .csv filepath
    
    
       output$ForwardText  =  renderText({list.files(as.character(FileDirectory()), 
                                                     pattern = as.character(ForwardSearchString()), full.names=TRUE, 
                                                     ignore.case=TRUE)
                                                      })
    
      }
    
    shinyApp(server = server, ui = ui)
    

2 个答案:

答案 0 :(得分:2)

Shiny有一个名为downloadButton的小部件,可以找到文档here

我已整合到您的应用中:

library(shiny)


ui <- fluidPage(

  # Date input by user
  dateInput(inputId = "NaVDate", label = "Select NaV Date", 
            format = "yyyy-mm-dd", startview = "month", weekstart = 0),
  # 
  textInput(inputId = "FundID", label = "Enter Fund ID (Numeric Only)", value = "", width = NULL, placeholder = NULL),

  downloadButton("downloadData", "Download")

)

server <- function(input, output) {

  # extract inputed month / year / day and vectorize ( inputed in YYYY-MM-DD format)


  timestrip   <- reactive({unlist(strsplit(as.character(input$NaVDate), split = ""))}) 

  Forwards_Fund  <- reactive({
    year   <- paste(timestrip()[1], timestrip()[2], timestrip()[3], timestrip()[4], sep = "")
    month  <- paste(timestrip()[6], timestrip()[7], sep = "")
    day    <- paste(timestrip()[9], timestrip()[10], sep = "")

    Date      = paste(year, month, day, sep = "")


    # create directory search criteria for the required files - eg.("XCP4P487FOFFET_20160315.CSV")

    Forwards  = paste0("*FOFFET_", Date, ".CSV$")


    # create main directory file path

    file_path <- paste0("C:/Users/dell Optiplex/Desktop/Equilibrium Weekly Macro/", year,"/", month) 


    # Search through file_path for criteria and create individual .csv filepath

    Forwards_CSV_path  = list.files(file_path, 
                                  pattern = Forwards, full.names=TRUE, 
                                  ignore.case=TRUE)


    # Read Data from CSV files

    Forwards_data = do.call(rbind, lapply(Forwards_CSV_path, function(x) read.csv(x, sep = ";", stringsAsFactors = FALSE)))


    # Extract data from the inputed fund code (input$FundID) 


    Forwards_data[which(Forwards_data$Fund.Code == input$FundID),]
  })

  output$downloadData <- downloadHandler(
    filename = function() {
      paste('data-', Sys.Date(), '.csv', sep='')
    },
    content = function(con) {
      write.csv(Forwards_Fund(), con)
    }
  )

}

shinyApp(server = server, ui = ui)

答案 1 :(得分:1)

这是一个带有操作按钮的示例程序,该按钮仅在单击时写入csv。不会将它集成到您​​的程序中,因为您的程序太大而且我没有您的数据,但您应该能够使用它:

library(shiny)
library(ggplot2)
u <- shinyUI(fluidPage(
  titlePanel("Simple Shiny Input"),

  sidebarLayout(position = "left",
                sidebarPanel( 
                              actionButton("savebutton", "Save Data"),
                              sliderInput("cnt","Count:",100,1000,500,5)
                ),
                mainPanel(plotOutput('stdplot'))
  )
))
s <- shinyServer(function(input, output) 
{
  histdata <- reactive({
      set.seed(1234)
      df <- data.frame(x=rnorm(input$cnt))
    } )
  output$stdplot = renderPlot({
      qplot(data=histdata(),x,fill=I("blue"),bins=30)
    })
  savedata <- observe({ 
        input$savebutton
        if (input$savebutton>0){
           write.csv(histdata(),"histo.csv")
        }
      })
  })
shinyApp(ui=u,server=s)

看起来像这样:

enter image description here