0

I´m trying to add rows to a dataframe based on the widget selection when a button is clicked.

I´ve put the observeEvent inside the renderTable, but the app returns an error: cannot coerce class "c("Observer", "R6")" to a data.frame.

This is the test dataframe to add rows to:

> DF <- data.frame(matrix(c("A","B"), ncol = 2), stringsAsFactors = FALSE)
> colnames(DF) <- c("col1", "col2")
> DF
  col1 col2
1    A    B

And this is the shiny app code:

library(shiny)

DF <- data.frame(matrix(c("A","B"), ncol = 2), stringsAsFactors = FALSE)
colnames(DF) <- c("col1", "col2")

ui <- fluidPage(

  titlePanel("Save input"),

  sidebarLayout(
    sidebarPanel(

      wellPanel(
        h3("Widget 1"),
        radioButtons("add", "Letter", c("A", "B", "C"))
      ),

      wellPanel(
        h3("Save button"),
        actionButton("save", "Save")       
      )
    ),

    mainPanel(
      tableOutput("table")
    )
  )
)

server <- function(input, output) {

  output$table <- renderTable({
    DF

    observeEvent(input$save, {
      l <- nrow(DF)
      DF[l+1,] <- list(input$add, input$add)
    })

  })

}

shinyApp(ui = ui, server = server)

App

Do you know what is wrong?

UPDATE:

With @Rémi answer the error is gone but the app does not add new rows to the table: app

AleG
  • 153
  • 8

1 Answers1

0

If you just want to display your table you should put the DF after observeEvent because "observeEvent returns an observer reference class object" so when you have a renderTable you must return a matrix or a data.frame.

server <- function(input, output) {
  output$table <- renderTable({
    observeEvent(input$save, {
      l <- nrow(DF)
      DF[l+1,] <- list(input$add, input$add)
    })
    DF
  })
}

Edit 1 : If I well understand your request, you don't need to save the data frame but you want to add row, it could be the same, you just need to use rbind as sugest the following post :

Add row to shinyTable

Rémi Coulaud
  • 1,684
  • 1
  • 8
  • 19
  • hey @Rémi, that solves the error but the app doesn´t add a new row to the table when you click the button, please see the screenshot in the update in the OP. – AleG Jun 12 '19 at 05:21