tonykuoyj
tonykuoyj

Reputation: 101

How to use multiple action buttons in R Shiny to manipulate a data frame consecutively?

I am trying to build a Shiny App with 4 action buttons that manipulate 1 data frame. I tried to make my action buttons working on the data frame consecutively, say, by clicking the Delete The First Row 49 times and I can get the last row of cars. I've written a ui.R for that:

#ui.R
shinyUI(pageWithSidebar(
  headerPanel("actionButton test"),
  sidebarPanel(
    actionButton("delete_top_1", "Delete The First Row"),
    p("Click the button to delete the first row"),
    #cars[-1, ]
    br(),
    actionButton("delete_last_1", "Delete the Last Row"),
    p("Click the button to delete the last row"),
    #cars[-nrow(cars), ]
    br(),
    actionButton("delete_top_2", "Delete the Top 2 Rows"),
    p("Click the button to delete the top 2 rows"),
    #cars[-1:-2, ]
    br(),
    actionButton("delete_last_2", "Delete the Last 2 Rows"),
    p("Click the button to delete the last 2 rows")
    #cars[-nrow(cars):-(nrow(cars)-1), ]
  ),
  mainPanel(
    tableOutput('view')
  )
))

However, I am stuck with the server.R part, I am thinking about using a reactiveValue() to replace cars. Could someone give me sample codes on the server.R part?

Upvotes: 1

Views: 3527

Answers (1)

GyD
GyD

Reputation: 4072

Using reactiveValues() is indeed the right choice for managing state.

I used mtcars dataset for presentation purposes.

library(shiny)
library(datasets)

ui <- shinyUI(pageWithSidebar(
  headerPanel("actionButton test"),
  sidebarPanel(
    actionButton("delete_top_1", "Delete The First Row"),
    p("Click the button to delete the first row"),
    #cars[-1, ]
    br(),
    actionButton("delete_last_1", "Delete the Last Row"),
    p("Click the button to delete the last row"),
    #cars[-nrow(cars), ]
    br(),
    actionButton("delete_top_2", "Delete the Top 2 Rows"),
    p("Click the button to delete the top 2 rows"),
    #cars[-1:-2, ]
    br(),
    actionButton("delete_last_2", "Delete the Last 2 Rows"),
    p("Click the button to delete the last 2 rows")
    #cars[-nrow(cars):-(nrow(cars)-1), ]
  ),
  mainPanel(
    tableOutput('view')
  )
))

server <- function(input, output, session){
  vals <- reactiveValues(data = mtcars) # Initialize vals$data

  observeEvent(input$delete_top_1, vals$data <- vals$data[-1, ])
  observeEvent(input$delete_top_2, vals$data <- vals$data[-c(1,2), ])
  observeEvent(input$delete_last_1, vals$data <- vals$data[-nrow(vals$data), ])
  observeEvent(input$delete_last_2, vals$data <- vals$data[-c(nrow(vals$data) - 1, nrow(vals$data)), ])

  output$view <- renderTable(vals$data)

}

shinyApp(ui, server)

Upvotes: 3

Related Questions