我有以下简单闪亮的应用程序,您可以在保存为 app.R 后继续运行
library(shiny)
library(DT)
DF <- data.frame(x = formatC(c(1, 2, 3), width = 10),
y = formatC(c(5, 4, 6), width = 5),
z = formatC(c(9, 5, 5), width = -5))
ui <- fluidPage(sidebarLayout(
sidebarPanel(
downloadButton(outputId = "down", label = "Download table")
),
mainPanel(DTOutput("table"))
))
server <- function(input, output, session) {
#Dataframe read in as a reactive expression
df <- reactive({
DF
})
#Output data frame as editable data table.
output$table <- renderDT({
datatable(df(), editable = 'cell', rownames = F)
}, server = FALSE)
#Add download button
output$down <- downloadHandler(
filename = function() {
paste("table", Sys.Date(), ".txt", sep="")
},
content = function(file) {
write.table(df(), file,
quote = FALSE,
col.names = FALSE,
row.names = FALSE)
}
)
}
shinyApp(ui, server)
首先,我正在制作一个具有非常特定格式的表格
DF
。单击“下载表格”按钮继续查看输出格式。接下来在代码中,我将该数据框设为反应式表达式df
。该应用程序显示一个可编辑的表格。如果双击任何单元格,您可以更改该单元格的值,但是更改不会记录在下载的表格中,因为它不会更新 df
反应表达式。我想使用 observer
函数来记录已更改的单元格并更新 df
或新的 reactiveVal
以便我可以使用下载处理程序下载具有指定格式的更新数据。
注意:在
buttons = c('copy', 'excel')
函数中使用datatable
调用并不是我想在这里做的。如果我这样做,我将丢失我最初为该数据框定义的格式。
目标:
我想我需要使用
reactiveVal
但我对这些功能仍然有点模糊。
非常感谢任何帮助!!
使用
editData
包中的DT
:
library(shiny)
library(DT)
ui <- fluidPage(sidebarLayout(
sidebarPanel(
downloadButton(outputId = "down", label = "Download table")
),
mainPanel(DTOutput("table"))
))
server <- function(input, output, session) {
rv <- reactiveValues()
#Dataframe read in as a reactive expression
observe({
rv$df <- iris
})
#Output data frame as editable data table.
output$table <- renderDT({
datatable(rv$df, editable = 'cell', rownames = FALSE)}, server = TRUE)
proxy = dataTableProxy('table')
observeEvent(input$table_cell_edit, {
print(input$table_cell_edit)
rv$df <<- editData(rv$df, input$table_cell_edit, 'table', rownames = FALSE)
})
#Add download button
output$down <- downloadHandler(
filename = function() {
paste("table", Sys.Date(), ".txt", sep="")
},
content = function(file) {
write.table(rv$df, file,
quote = FALSE,
col.names = FALSE,
row.names = FALSE)
}
)
}
shinyApp(ui, server)