Write list of lists into a file in R/Shiny

254 Views Asked by At

I have a list of lists which I would like to write into a file (.txt or .xlsx) in Shiny.

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)))

In R, I could use the sink command like :

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

Which the outcome is a txt file :

$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"

How could I use this sink function in Shiny to provide a download option for the user to download C ? and how could I remove the row index in the output ?

I have tried print(C,row.names = FALSE), but it doesn't work.

my desired output should look like this :

$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

There are 1 best solutions below

3
On BEST ANSWER

Downloading file using shiny is very similar to usual R way. You need to:

  1. create download button in UI (general for all download types)
  2. Specify sink function on server download part

For example:

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)