首页 > 解决方案 > R Shiny,对作为输入的数据应用已实现的函数

问题描述

我想实现一个将 .csv 文件作为输入的应用程序(用户从他的计算机中选择文件),然后我想将此文件作为我之前实现的函数“f”中的参数。

我可以给你 ui.R 和 server.R

用户界面

library(shiny)

shinyUI(fluidPage(
  sidebarLayout(
    sidebarPanel(
      fileInput("file",
                "Put your portfolio data here",
                accept=c(".csv")
                )
    ),

    mainPanel(tableOutput("table"))
  )

))

服务器.R

library(shiny)



shinyServer(function(input, output) {

    data <- reactive({
      file1 <- input$file
      if(is.null(file1)){return()} 
      read.csv2(file=file1$datapath)
    })


    #to view the data    
    output$table <- renderTable({
      if(is.null(data())){return ()}
      data()
    })

})

最后,我的函数“f”应该提供一个 .csv 文件作为输出。

标签: rdataframeinputshiny

解决方案


用户界面

library(shiny)

shinyUI(fluidPage(
  sidebarLayout(
    sidebarPanel(
      fileInput("file",
                "Put your portfolio data here",
                accept=c(".csv")
                ),
      downloadButton(download_data.csv, "Download File")
    ),

    mainPanel(tableOutput("table"))
  )

))

服务器.R

shinyServer(function(input, output) {

    data <- reactive({
      file1 <- input$file
      if(is.null(file1)){return()} 
      read.csv2(file=file1$datapath)
    })


    #to view the data    
    output$table <- renderTable({
      if(is.null(data())){return ()}
      data()
    })

    # to download the tadata
    output$download_data.csv <- downloadHandler(

    filename = "download_data.csv",
    content = function(file){

      data <- data() # At this point you should have done the transformation 
                     # to the data

      write.csv(data, file, row.names = F)

    }

  )


})

推荐阅读