I am trying to add a row index column to a reactive data frame created on-the-fly from user inputs. I am able to do this outside of Shiny using the tibble::rowid_to_column function but cannot make it work in the below Shiny app (line 44). Can someone please provide guidance on how to make it work? Also, when I delete a row from the data frame, how can we make rowid numbers sequential again? Thanks.
library(shiny)
library(DT)
library(tidyverse)
input_data <- data.frame(
# rowid = double(),
input1 = character(),
input2 = double(),
stringsAsFactors = FALSE)
ui <- fluidPage(
titlePanel("Title"),
sidebarLayout(
sidebarPanel(
selectInput("input1",
"Input 1",
choices = c("Value 1", "Value 2", "Value 3")),
numericInput("input2",
"Input 2",
value = 100),
actionButton("add_btn",
"Add Row"),
actionButton("delete_btn",
"Delete Row"),
actionButton("reset_btn",
"Reset"),
position = "left"
),
mainPanel(
DT::dataTableOutput("input_table")
)
)
)
server <- function(input, output) {
input_table <- reactiveVal(input_data)
observeEvent(input$add_btn, {
t = rbind(input_table(), data.frame(col1 = input$input1, col2 = input$input2))
# %>%
# cbind(tibble::rowid_to_column("rowid"))
input_table(t)
})
observeEvent(input$delete_btn, {
t = input_table()
print(input$input_table_rows_selected)
if (!is.null(input$input_table_rows_selected)) {
t <- t[-input$input_table_rows_selected,]
}
input_table(t)
})
observeEvent(input$reset_btn, {
input_table(input_data)
})
output$input_table <- DT::renderDataTable({
datatable(input_table())
})
}
shinyApp(ui = ui, server = server)