如何使用R Shiny中的多个动作按钮连续操作数据帧?

时间:2016-09-10 04:48:11

标签: r shiny

我正在尝试构建一个带有4个操作按钮的Shiny应用程序来操作1个数据框。我试图让我的操作按钮连续处理数据框,例如,点击删除第一行 49次,我可以获得cars的最后一行。我为此写了一个ui.R:

#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')
  )
))

但是,我坚持使用服务器。部分,我正在考虑使用reactiveValue()来替换cars。有人可以在server.R部分给我示例代码吗?

1 个答案:

答案 0 :(得分:1)

使用reactiveValues()确实是管理州的正确选择。

我使用mtcars数据集进行演示。

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)