首页 > 解决方案 > 如何将可编辑的行和列以交互方式插入(和删除)到使用 R Shiny 中的 DT 包呈现的数据表中?

问题描述

在下面的 MWE 代码中,如何修改它以允许用户从使用 DT 包呈现的表中插入新的行或列,或删除指定的行或列?

下面已经允许用户通过单击它们来编辑字段。接下来,为了使其更具交互性,我希望用户能够添加/删除行和列。任何添加的列或行都将与当前字段一样可编辑。

底部的图像有助于说明我正在尝试做的事情。

起草的情节还不是 100%。最终,我将为表格中的每一列绘制一条单独的线。

MWE代码:

library(shiny)
library(DT)
library(tidyverse)

  ui <- fluidPage(
  titlePanel("Editable Dataframe and Plot"),
  sidebarLayout(
    sidebarPanel(
      DTOutput("my_datatable"),
      h5(strong("Add/delete row/column by name:")),
      fluidRow(
        tags$head(tags$style(
           type= "text/css",
                "label{display:table-cell;
                 text-align:center;
                 vertical-align:middle;}.form-group{display:table-row;}"
            ) # close tags style
          ), # close tags head
        textInput('Row','Row >'),
        textInput('Col','Column >')
        ), # close fluid row
      br(),
      actionButton("addBtn", "Add"),
      actionButton("removeBtn","Remove"),
      actionButton("plotData",label = "Plot")
    ), # close sidebar panel
    
    # Show plot
    mainPanel(plotOutput("my_plot"))
    
  ) # close sidebar layout
) # close fluid page

server <- function(input, output) {
  v <- reactiveValues(data = { 
    data.frame(x = numeric(0),y = numeric(0)) %>% 
      add_row(x = rep(0,10),y = rep(0,10))
  }) # close reactive values
  
  output$my_datatable <- renderDT({
    DT::datatable(v$data, editable = TRUE, options = list(dom = 'ltipr'))
  }) # close render DT

  observeEvent(input$my_datatable_cell_edit, {
    info = input$my_datatable_cell_edit
    i = as.numeric(info$row)
    j = as.numeric(info$col)
    k = as.numeric(info$value)
    if(k < 0){k <- k * -1} # Convert to positive if negative
    v$data[i,j] <- k
  }) # close observe event
  
  # Render plot
  output$my_plot <- renderPlot({
    req(input$plotData) # Require the input button to be non-0 (ie: don't load the plot when the app first loads)
    isolate(v$data) %>%  # Don't react to any changes in the data
      ggplot(aes(x,y)) +
      geom_line()
  }) # close render plot
} # close server

shinyApp(ui = ui, server = server)

第一张图片显示了调用应用程序时呈现的内容。第二张图片是用户删除一行的示例。第三张图片是用户插入列的示例。

在此处输入图像描述

在此处输入图像描述

在此处输入图像描述

标签: rshinydt

解决方案


推荐阅读