在可编辑renderDT对象中更改值后更新Shiny DT&SQLite

时间:2018-11-03 18:14:10

标签: r sqlite shiny shinydashboard dt

我已经为可编辑的SQLite成员数据库仪表板创建了Shiny app。我的计划是使用DT和DBI程序包来编辑特定值,然后通过删除旧的并将新的写入其位置来将更新推回到SQLite表中(尚未对删除表进行编码,但是会进入按钮操作)。

UI端的行为符合预期,但是当我编辑页面并单击“写入表”按钮,然后重新加载或关闭该应用程序时,它看起来不像DT或数据库已更新。

我的问题(除了“如何工作?”之外):

  1. 当可编辑功能正常工作时,它是编辑long_sepal还是数据?
  2. 我应该能够在Global环境中看到更新吗?

下面我使用Iris.db作为数据集包含了reprex。

谢谢! -贾斯汀

library(shiny)
require(shinydashboard)
library(dplyr)
library(RSQLite)
library(DBI)
library(dbplyr)
library(dplyr)
library(DT)

#create SQLite connection and open it
con <- DBI::dbConnect(RSQLite::SQLite(), 
                      "/Users/admin/ICG/iris.db")

src_dbi(con)

#split SQLite datatable into two seperate datatables
data <- tbl(con, "data")
data <- data %>% as.data.frame()
long_sepal <- filter(data, sepal_length>5.5)
short_sepal <- filter(data, sepal_length<5.5)

header <- dashboardHeader(title="Iris Dashboard")

#sidebar with "Write to DB" reactive button
sidebar <- dashboardSidebar(sidebarMenu(
  div(style="display:inline-block;width:32%;text-align: 
      center;",actionButton("action", label = "Write to 
                            DB"))))

#Body element of the dashboard
frow1 <- fluidRow(
  
  box(
    title = "Long Sepal"
    ,status = "primary"
    ,solidHeader = TRUE 
    ,collapsible = TRUE 
    ,DTOutput("table1", height = "300px")
  )
  
  ,box(
    title = "Short Sepal"
    ,status = "primary"
    ,solidHeader = TRUE 
    ,collapsible = TRUE 
    ,DT::dataTableOutput(outputId = "table2", height = 
                           "300px")
  )    
)
# merge into dashBoard body
body <- dashboardBody(frow1)

# Define UI for dashboard page and 
ui <- dashboardPage(title = 'Iris Dashboard', 
                     header, sidebar,
                    body, skin = 'black'
)

# Define server logic required for editable tables
server <- function(input, output) {  
  
  output$table1 <- renderDT(long_sepal, options = 
                              list(scrollX = TRUE), editable = TRUE)
  output$table2 <- renderDT(short_sepal, options = 
                              list(scrollX = TRUE), editable = TRUE)
  
  #necessary code to replace data once edited
  proxy1 = dataTableProxy('table1')
  
  observeEvent(input$x2_cell_edit, {
    info = input$x2_cell_edit
    str(info)
    i = info$row
    j = info$col
    v = info$value
    long_sepal[i, j] <<- DT::coerceValue(v, 
                                            long_sepal[i, j])
    replaceData(proxy1, long_sepal, resetPaging = 
                  TRUE)  # important
  })
  
  #Write to SQLite database
  data <- eventReactive(input$action, {
    dbWriteTable(con, "data", data.frame(data), append 
                 = TRUE)
    data <- dbReadTable(con, "data")
    return(data)
  })  
}

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

0 个答案:

没有答案