Search code examples
rshinyshinydashboardrshiny

How can we get the datatable to appear in the mainpanel while using shiny dashboard?


in the R shiny code below have "browse," "SplitColumn," and "DeleteRows". When a user uploads a CSV file using the browse button, the Datatable should appear in the main panel, but it presently does not.

If the datable appears in the mainpanel, I'll be able to use the "SplitColumn" and "DeleteRows" buttons.

Could someone assist me in resolving this problem?

csv data

ID  Type   Range
21  A1 B1   100
22  C1 D1   200
23  E1 F1   300

app.R

library(shiny)
library(shinydashboard)
library(reshape2)
library(DT)

splitColumn <- function(data, column_name) {
  newColNames <- c("Unmerged_type1", "Unmerged_type2")
  newCols <- colsplit(data[[column_name]], " ", newColNames)
  after_merge <- cbind(data, newCols)
  after_merge[[column_name]] <- NULL
  after_merge
}

ui <- dashboardPage(
  dashboardHeader(title = "Basic dashboard"),
  dashboardSidebar(),
  dashboardBody(
    fluidRow(
      fileInput("file1","Uplaod Data",buttonLabel = "Browse..",placeholder = "No file Selected"),
      checkboxInput("header", "Header", TRUE),
      #actionButton("Splitcolumn", "SplitColumn"),
      selectInput(inputId='selectcolumn', label='select column', ''),
      #actionButton("deleteRows", "Delete Rows")
    ),
    fluidRow(
      column(3,
             actionButton("Splitcolumn", 'SplitColumn')
      ),
      column(3,
             actionButton("deleteRows", "Delete Rows")
      ),
     
    )
   
  ),
  mainPanel(
    DTOutput("table1")
)
)

server <- function(session, input, output) {
  rv <- reactiveValues(data = NULL)
  
  observeEvent(input$file1, {
    file <- input$file1
    ext <- tools::file_ext(file$datapath)
    
    req(file)
    
    validate(need(ext == "csv", "Please upload a csv file"))
    
    rv$data <- read.csv(file$datapath, header = input$header)
    
    updateSelectInput(session, 'selectcolumn', 'select column', names(rv$data))
    
  })
  
  observeEvent(input$Splitcolumn, {
    rv$data <- splitColumn(rv$data, input$selectcolumn)
  })
  
  observeEvent(input$deleteRows,{
    if (!is.null(input$table1_rows_selected)) {
      rv$data <- rv$data[-as.numeric(input$table1_rows_selected),]
    }
  })
  
  output$table1 <- renderDT({
    rv$data
  })
}

shinyApp(ui, server)

Solution

  • Your mainPanel(DTOutput("table1") code should be inside the dashboardBody function. because you are using fluidRow here, you must also have the mainPanel within the fluidRow(). With this change the table appears when a .csv file is uploaded, and the splitColumn function seems to work, but i do not understand the purpose.