【问题标题】:Write list of lists into a file in R/Shiny将列表列表写入 R/Shiny 中的文件
【发布时间】:2018-09-29 10:30:13
【问题描述】:

我有一个列表列表,我想在 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"

【问题讨论】:

    标签: r download shiny sink


    【解决方案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)  
    

    【讨论】:

    • 感谢您的回复,但返回错误:Listening on http://127.0.0.1:6609 Error opening file: 32 Error reading: 6
    • 找到了,你应该在`print(C)'后面加上sink(),但是现在我怎样才能删除行索引呢?
    • @user9112767 是的,它可以在闪亮的服务器上工作,因为界面将通过用户计算机。从多级列表中的对象中删除行号要复杂得多,并且与原始问题没有真正的关系。您可以删除已接受的答案标记。
    猜你喜欢
    • 1970-01-01
    • 2018-06-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-17
    • 1970-01-01
    相关资源
    最近更新 更多