Home > Software design >  Adding row to Table removes all previous data in R shiny
Adding row to Table removes all previous data in R shiny

Time:08-24

I'm working on a shiny dashboard app, where i'm trying to add new rows to a table when clicking a button. When clicking, data is gathered from multiple input elements, collected in a list, which is then added as a new row. However, while the row is added, all previous rows become 'NA'.

Server code:

    RowList <- c()
    dfRowList <<- data.frame(matrix(ncol = 13, nrow = 0))
    colnames(dfRowList) <<- c(# list of row properties #)

    observeEvent(input$AddRow, {
      Newrow <- paste0("R", length(RowList)   1)
      RowList <<- append(RowList, NewRow)

      RProps <- c()
      RProps <- c(NewRow)
      for (prop in c(# list of row properties #)){
        Propvalue <- input[[paste0("R", prop)]]
        RProps <- append(RProps, Propvalue)
      }
      
      dfRowList[length(RowList),] <- RProps
      
      output$RowList <- renderTable(dfRowList)
    })

When using rbind() no new rows are created, just the 1 row is replaced by the new values and the column names are screwed over :/

I checked all other values. Creation of new row names, properties and lists works fine. When i use View(dfRowList) to look at the dataframe itself, it also shows the same problem (so its not a rendering problem). So, only adding the row does not work.

Does someone know what's going on here?

Thanks a lot in advance!

CodePudding user response:

A minimal working example based on the repository already posted:

library(shiny)
library(data.table)

df = data.frame(Column1=character(), Column2=numeric())

ui <- fluidPage(

  sidebarPanel(
    textInput("input1", "First Input: (character)", "test"),
    numericInput("input2", "Second Input: (numeric)", min = 1, max = 10, value = 1),
    actionButton("add", "Add Data"),
  ),
  mainPanel(
    tabsetPanel(
      tabPanel("table", value = 1, DT::dataTableOutput("showtable"))
    )
  )
)

server <- function(input, output) {

  data_table <- reactiveVal(df)
  
  observeEvent(input$add, {
    t = rbind(data.frame(Column1 = input$input1,
                         Column2 = input$input2),data_table())
    data_table(t)
  })
  
  output$showtable <- DT::renderDataTable({
    data.table::data.table(data_table())
  })
}

# Run the application 
shinyApp(ui = ui, server = server)
  • Related