首页 > 解决方案 > R Shiny - 反应数据帧下载到 csv

问题描述

我制作了一个允许用户上传多个 csv 文件的应用程序。

然后这些 csvs 'rbind' 在一起,'read.csv' 并在 df 中添加了一个列,即文件名。

然后处理 df 以生成可下载的各种图。这完美地工作。但是,当我尝试从反应元素中下载特定的数据帧时,我无法让它工作。

在这个例子中,我想从 testinput 反应函数中下载df1 。

用户界面:

    dashboardPage( skin = "black",
   dashboardHeader(title = "myApp"),
   dashboardSidebar(collapsed = TRUE,
   sidebarMenu(
    menuItem("Home", tabName = "dashboard1", icon = icon("home", lib = 
  "glyphicon"))
    ) 
    ),
   dashboardBody(
     tags$head(tags$style(HTML('
      .main-header .logo {
                          font-family: "Times New Roman", serif;
                          font-weight: bold;
                          font-size: 24px;
                          }
                          '))),

tabItems(
  tabItem(tabName = "dashboard1",
          fileInput("file1",
                    label="Input files:",
                    multiple = TRUE),
          downloadButton('downloadData', 'Download Data')
  )
  )

)
)

服务器:

     library(shiny)
     library(shinydashboard)

     #server start
     function(input, output) {

       testinput<- reactive({
if(is.null(input$file1))
  return ()
else 
{
  nfiles = nrow(input$file1) 
  csv = list()
  for (i in 1 : nfiles)
  {

    csv[[i]] = read.csv(input$file1$datapath[i])

  }

  csv_names <- input$file1[['name']]
    actual_names<-input$statics$name
  df1<-cbind(actual_names, csv_names)
  mydata <- do.call(rbind, lapply(csv_names, function(x) cbind(read.csv(x), name=strsplit(x,'\\.')[[1]][1])))
    df1<-cbind(df1, mydata)    
  }
   })

     output$downloadData <- downloadHandler(
filename = function() { paste(input$downloadData, " ",Sys.Date(),".csv",sep="") },
content = function(file) {
  write.csv(df1,file)
}
    )

 )


   }

任何帮助都会很棒,因为我搜索了很多 SO 和其他论坛,但我很困惑。

标签: rshinyevent-handlingshiny-servershiny-reactivity

解决方案


@Chabo 是正确的:

我必须创建一个新的 reactive(),然后将其作为 output$ 渲染到我的 UI。

然后我可以下载反应事件


推荐阅读