首页 文章

将列表列表写入R / Shiny中的文件

提问于
浏览
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中使用此接收器功能为用户提供下载选项 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"

1 回答

  • 1

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

    • 在UI中创建下载按钮(适用于所有下载类型)

    • 在服务器下载部分指定 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)
    

相关问题