根据可编辑单元格用户输入更新闪亮的DT

时间:2020-09-10 17:08:13

标签: r shiny dt

一个闪亮的小应用示例:

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

ui <- fluidPage(

    # Application title
    titlePanel("blah"),

    sidebarLayout(
        sidebarPanel(
            sliderInput("bins",
                        "Number of bins:",
                        min = 1,
                        max = 50,
                        value = 30)
        ),

        # Show a plot of the generated distribution
        mainPanel(
           DT::DTOutput('ex_table')
        )
    )
)

server <- function(input, output) {

    output$ex_table <- DT::renderDataTable(mtcars %>% select(cyl) %>% mutate(blah = cyl + 2), 
                                           selection = 'none', editable = TRUE)
}

# Run the application 
shinyApp(ui = ui, server = server)

如果运行,它看起来像: enter image description here

自从我在editable = TRUE中添加了renderDataTable()以来,您就可以编辑单元格。

提供数据表的表的行如下:

mtcars %>% select(cyl) %>% mutate(blah = cyl + 2)

所以功能'blah'应该总是cyl + 2中的值。在屏幕快照中,我添加了10,000,因此所需的输出将是数据表在按Enter键后更新为显示10,002。

这可能吗?我该怎么办?

1 个答案:

答案 0 :(得分:1)

您可以遵循以下examples
试试:

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

ui <- fluidPage(
  
  # Application title
  titlePanel("blah"),
  
  sidebarLayout(
    sidebarPanel(
      sliderInput("bins",
                  "Number of bins:",
                  min = 1,
                  max = 50,
                  value = 30)
    ),
    
    # Show a plot of the generated distribution
    mainPanel(
      DT::DTOutput('modtable'),
    )
  )
)

server <- function(input, output,session) {
  data <- mtcars %>% select(cyl) %>% mutate(blah = cyl + 2)
  
  output$modtable <- DT::renderDT(data, selection = 'none', editable = TRUE)
  
  proxy = dataTableProxy('modtable')

  observeEvent(input$modtable_cell_edit, {
    info = input$modtable_cell_edit
    str(info)
    i = info$row
    j = info$col
    v = info$value
    data <<- editData(data, info)
    if(j==1){data[i,j+1]<<-as.numeric(data[i,j])+2}
    replaceData(proxy, data, resetPaging = FALSE) 
  })

}

# Run the application 
shinyApp(ui = ui, server = server)

enter image description here