繁体   English   中英

R 闪亮:保存来自多个面板的数据框

[英]R shiny: save data frames from multiple panels

在下面的应用程序中,我想添加一个全局按钮,以同时保存 2 个面板中的表格。 理想情况下,它们应该保存到 xlsx 文件中,以相应选项卡命名的选项卡中。 请注意,选项卡是使用模块创建的。

非常感谢!!

library(shiny)
library(DT)

modDtUi <- function(id){ # UI module
  ns = NS(id)
  DT::dataTableOutput(ns('x1'))
}


modDt <-  function(input, output, session, data, globalSession){ # Server module
  
  x <- data
  output$x1 <- DT::renderDataTable(x, selection = 'none', editable = TRUE)
  
  proxy <- dataTableProxy('x1', session = globalSession)
  

  
}



ui <- fluidPage(
  mainPanel(
    tabsetPanel(
    
      tabPanel("Table1", modDtUi("editable")),
      tabPanel("Table2", modDtUi("editable2"))
    )
  )
)


server <- function(input, output, session) {
  callModule(modDt,"editable", data = head(iris,10), globalSession = session)
  
  callModule(modDt,"editable2", data = tail(iris,5), globalSession = session)
}

shinyApp(ui = ui, server = server)


我相信这个演示是有效的。

我使用reactiveValues v$data来存储模块内的数据。 该模块将return v$data以便在您想将数据保存在闪亮的server时可以检索它。

我还添加了一个observeEvent来检测数据的变化,并使用replaceData更新数据表。

excel 文件是使用writexl库创建的,但您当然可以用其他库替换。

让我知道这是否适合您。 我想这个答案的一些元素可以改进 - 如果我们能识别它们,希望进一步编辑。

library(shiny)
library(DT)
library(writexl)

modDtUi <- function(id){ # UI module
  ns = NS(id)
  DT::dataTableOutput(ns(id))
}

modDt <-  function(input, output, session, data, id, globalSession){ # Server module
  
  v <- reactiveValues(data = data)
  
  output[[id]] <- DT::renderDataTable(v$data, selection = 'none', editable = TRUE)
  
  proxy <- dataTableProxy(id, session = globalSession)
  
  id_input = paste(id, "cell_edit", sep = "_")
  
  # Could add observeEvent here to detect edit event
  observeEvent(input[[id_input]], {
    info = input[[id_input]]
    if (!is.null(info)) {
      v$data[info$row, info$col] <<- DT::coerceValue(info$value, v$data[info$row, info$col])
    }
    replaceData(proxy, v$data, resetPaging = FALSE)
  })
  
  return(data = reactive({v$data}))
}

ui <- fluidPage(
  sidebarLayout(
    sidebarPanel(
      width = 2,
      actionButton("btn", "Save Both")
    ),
    mainPanel(
      tabsetPanel(
        tabPanel("Table1", modDtUi("editable1")),
        tabPanel("Table2", modDtUi("editable2"))
      )
    )
  )
)

server <- function(input, output, session) {
  
  e1 <- callModule(modDt, "editable1", data = head(iris,10), id = "editable1", globalSession = session)
  e2 <- callModule(modDt, "editable2", data = tail(iris,5), id = "editable2", globalSession = session)
  
  observeEvent(input$btn, {
    print("Saving...")
    sheets <- list("e1" = e1(), "e2" = e2())
    write_xlsx(sheets, "test.xlsx")
  })
  
}

shinyApp(ui = ui, server = server)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM