2

我有一个列表列表,我想在 Shiny 中写入文件(.txt 或 .xlsx)。

C = list(listA = list(1:3, structure(1:9, .Dim = c(3L, 3L)), 4:9), 
    listB = list(c("t1", "t2", "t3"), structure(c("p1", "p2"), .Dim = 2:1)))

在 R 中,我可以使用如下sink命令:

sink("test.txt")
print(mydata)
sink()

结果是一个txt文件:

$listA
$listA[[1]]
[1] 1 2 3

$listA[[2]]
     [,1] [,2] [,3]
[1,]    1    4    7
[2,]    2    5    8
[3,]    3    6    9

$listA[[3]]
[1] 4 5 6 7 8 9


$listB
$listB[[1]]
[1] "t1" "t2" "t3"

$listB[[2]]
     [,1]
[1,] "p1"
[2,] "p2"

如何在 Shiny 中使用这个 sink 功能为用户提供下载选项C?以及如何删除输出中的行索引?

我试过print(C,row.names = FALSE)了,但它不起作用。

我想要的输出应该是这样的:

$listA
$listA[[1]]
1 2 3

$listA[[2]]
     [,1] [,2] [,3]
1    4    7
2    5    8
3    6    9

$listA[[3]]
4 5 6 7 8 9


$listB
$listB[[1]]
"t1" "t2" "t3"

$listB[[2]]
     [,1]
"p1"
"p2"
4

1 回答 1

1

下载文件使用shiny与通常的 R 方式非常相似。你需要:

  1. 在 UI 中创建下载按钮(适用于所有下载类型)
  2. sink在服务器下载部分指定功能

例如:

library(shiny)

ui <- fluidPage(
    # Runs downloadHandler in server part
    downloadButton("downloadData", "Download This Data")
)

server <- function(input, output) {

    # Data to download  
    C <- list(listA = list(1:3, structure(1:9, .Dim = c(3L, 3L)), 4:9), 
              listB = list(c("t1", "t2", "t3"), structure(c("p1", "p2"), .Dim = 2:1)))

    # write C to file using sink
    output$downloadData <- downloadHandler(
        filename = function() {"text.txt"},
        content = function(file) {
            # Here you change to csv (write.csv) or excel (xlsx::write.xlsx)
            sink(file); print(C); sink()
        }
    )
}

shinyApp(ui, server)  
于 2018-09-29T10:40:36.073 回答