简体   繁体   中英

R Shiny: Transposing and displaying an user uploaded file

I am trying to build an app and I need to transpose the user uploaded table. With the code I have, I am able to read the user input and also display it in the app.

Following is my code:

library(shiny)

ui <- fluidPage(
  fileInput("file",
            "Upload file here"),
  checkboxInput("header", "Check if you have header", value = T),

  tableOutput("table"),
  tableOutput("tabletranspose")
)

server <- function(input, output, session){

  infile <- reactive({
    if (is.null(input$file)) return(NULL)
    read.csv(input$file$datapath, header = input$header)
  })

  # To display original user's table
  output$table <- renderTable({
    infile()
  })

  # To display transposed table
  output$tabletranspose <- renderTable({

    return(t(infile()))
  })
}

shinyApp(ui, server)

But when I run the code to get the transpose using t(infile()), I am getting this error:

Error in t.default: argument is not a matrix

How can I do this differently so that I would get desired result?

Thanks!

Youre renderTable function is running as soon as your app starts, an because no file was uploaded, it doesnt know how to transpose nothing. So you have to delay the reactivity with a req() function for example. You sould also check out validate + need or observeEvent and eventReactive functions, as with them you can control the reactive "flow" of your app.

This example should work, which waits for an uploaded file with req(input$file) .

library(shiny)

ui <- fluidPage(
  fileInput("file",
            "Upload file here"),
  checkboxInput("header", "Check if you have header", value = T),

  tableOutput("table"),
  tableOutput("tabletranspose")
)

server <- function(input, output, session){

  infile <- reactive({
    if (is.null(input$file)) return(NULL)
    read.csv(input$file$datapath, header = input$header)
  })

  # To display original user's table
  output$table <- renderTable({
    req(input$file)
    infile()
  })

  # To display transposed table
  output$tabletranspose <- renderTable({
    req(input$file)
    t(infile())
  })
}

shinyApp(ui, server)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM