[英]How to use write.table to download a dataframe into a nice csv/Excel file?
我正在嘗試使用 Shiny downloadHandler()
中的write.table()
函數,根據底部的可重現代碼將df
反應數據幀下載為 .csv 文件。 函數write.table()
允許刪除列名(我需要),但會導致非 Excel 輸出(問題 #1 ); 另一方面, write.csv()
會產生不錯的 Excel 輸出,但不允許刪除列名(問題 #2 )。
有沒有辦法讓write.table()
為 CSV 正常工作? 如果沒有,有沒有其他方法可以解決這個問題?
此圖顯示了問題:
可重現的代碼:
library(dplyr)
library(DT)
library(shiny)
library(shinyWidgets)
library(tidyverse)
ui <-
fluidPage(fluidRow(
column(width = 8,
h3("Click below to download:"),
downloadButton("sumsDownload","Download",style = "width:20%;"),
h3("Summed Data:"),
DT::dataTableOutput("sums")
)
))
server <- function(input, output, session) {
data <- reactive({
data.frame(
Period = c("2020-01", "2020-02", "2020-03", "2020-01", "2020-02", "2020-03"),
ColA = c(1000.01, 20, 30, 40, 50, 60),
ColB = c(15.06, 25, 35, 45, 55, 65)
)
})
summed_data <- reactive({
data() %>%
group_by(!!sym("Period")) %>%
select("ColA", "ColB") %>% summarise(across(everything(), sum))
})
output$sums <- renderDT({datatable(data = summed_data(),rownames = FALSE)})
df <- reactive({ # `df` modifies `summed_data` for csv download
as.data.frame(
rbind(
c("Summed Data",rep(NA,ncol(summed_data())-1)),
colnames(summed_data()),
matrix(unlist(summed_data(), use.names=FALSE),
nrow = nrow(summed_data()),
)
)
)
})
output$sumsDownload <- downloadHandler(
filename = function() {paste("sumsDownload","csv",sep=".")},
content = function(file){
write.table( # change this to write.csv to see Issue #2
df(),
na = "",
file,
col.names = FALSE, # comment out this line if changing to write.csv
row.names = FALSE)
}
)
}
shinyApp(ui, server)
以下是反映截至 2022 年 5 月 5 日發布的評論的已解決代碼:
library(dplyr)
library(DT)
library(shiny)
library(shinyWidgets)
library(tidyverse)
ui <-
fluidPage(fluidRow(
column(width = 8,
h3("Click below to download:"),
downloadButton("sumsDownload","Download",style = "width:20%;"),
h3("Summed Data:"),
DT::dataTableOutput("sums")
)
))
server <- function(input, output, session) {
data <- reactive({
data.frame(
Period = c("2020-01", "2020-02", "2020-03", "2020-01", "2020-02", "2020-03"),
ColA = c(1000.01, 20, 30, 40, 50, 60),
ColB = c(15.06, 25, 35, 45, 55, 65)
)
})
summed_data <- reactive({
data() %>%
group_by(!!sym("Period")) %>%
select("ColA", "ColB") %>% summarise(across(everything(), sum))
})
output$sums <- renderDT({datatable(data = summed_data(),rownames = FALSE)})
df <- reactive({ # `df` modifies `summed_data` for csv download
as.data.frame(
rbind(
c("Summed Data",rep(NA,ncol(summed_data())-1)),
colnames(summed_data()),
matrix(unlist(summed_data(), use.names=FALSE),
nrow = nrow(summed_data()),
)
)
)
})
output$sumsDownload <- downloadHandler(
filename = function() {paste("sumsDownload","csv",sep=".")},
content = function(file){
write.table(
df(),
na = "",
file,
sep = ",", # add this per road_to_quantdom on May/05/22
col.names = FALSE,
row.names = FALSE)
}
)
}
shinyApp(ui, server)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.