问题描述
我有一个基本的闪亮应用程序,希望用户选择一个数据集,然后能够下载没有列名的所选数据集。另外,我想在要下载的数据集中添加页眉和页脚记录。
标题记录= 0,MYFILE,20200917。
页脚记录= 9,[所选数据集中的行数],[对所选数据集的第一列求和]。
下面是我到目前为止的代码:
ui
library(shiny)
shinyUI(fluidPage(
titlePanel('File download'),sidebarLayout(
sidebarPanel(
selectInput("dataset","Choose a dataset:",choices = c("Rock","Pressure","Cars")),radioButtons("filetype","File type:",choices = c("csv","tsv")),downloadButton('downloadData','Download')
),mainPanel(
tableOutput('table')
)
)
))
服务器:
library(shiny)
library(tidyverse)
shinyServer(function(input,output) {
datasetInput <- reactive({
switch(input$dataset,"Rock" = rock,"Pressure" = pressure,"Cars" = cars)
})
output$table <- renderTable({
datasetinput()
})
output$downloadData <- downloadHandler(
filename = function() {
paste("myfile",input$dataset,gsub("-","",Sys.Date()),"_01_res.dat_00000002",sep = ".")
},content = function(file) {
# Write to a file specified by the 'file' argument
write.table(datasetinput(),file,row.names = FALSE,col.names = F,sep = ",")
}
)
})
以上代码到目前为止有效,但没有页眉和页脚记录。当我尝试将页眉和页脚记录添加到数据集时,它不起作用。
我只需要更改downloadHandler部分以添加页脚和标头记录,但是当我这样做时会出现错误。以下是我尝试过的方法:
output$downloadData <- downloadHandler(
filename = function() {
paste("myfile",content = function(file) {
# Write to a file specified by the 'file' argument
a = paste0("0,","MYFILE,Sys.Date()))
z = paste0("9,nrow(datasetInput),sum(datasetInput))
write.table(x = a,quote = F,row.names = F,sep = sep)
write.table(x = datasetinput(),append = T,sep = sep)
write.table(x = z,sep = sep)
}
)
我可以在没有Shiny的情况下在普通R文件中实现此目的。我这样做的方式是编写一个函数,然后如下所示调用该函数:
write_output <- function(a,df,z){
filename = paste("myfile","Rock",sep = "") %>% gsub( "-",.)
write.table(x = a,file = filename,row.names = F)
write.table(x = df,append = T)
write.table(x = z,append = T)
}
应用功能
write_output(a = paste0("0,"MyFILE,Sys.Date())),df = datasetInput,z = paste0("9,sum(datasetInput[,1])))
因此,简而言之,我需要输出带有页眉和页脚记录的数据集,该记录集的大小与数据集的大小不同。
以下是输出示例:第一行是页眉记录,其次是岩石数据集中的3行,最后一行是页脚
0,MyFILE,20200917
4990,2791.9,0.0903296,6.3
7002,3892.6,0.148622,6.3
7558,3930.66,0.183312,6.3
9,48,345011
任何帮助将不胜感激:)。谢谢
解决方法
我的代码中有多个分隔符,这使它感到困惑。我排除了其中一种论点,它奏效了。这是下载处理程序的新代码。
output $ downloadData
filename = function() {
paste("myfile",input$dataset,gsub("-","",Sys.Date()),sep = ".")
},content = function(file) {
# Write to a file specified by the 'file' argument
a = paste0("0,","MYFILE,Sys.Date()))
z = paste0("9,nrow(datasetInput()),sum(datasetInput()[,1]))
write.table(x = a,quote = F,sep = ",col.names = F,row.names = F,file)
write.table(x = datasetInput(),append = T,file)
write.table(x = z,file)
}
)