在應用程序上工作我來到一個(很多)小事情,我遇到了麻煩。閃亮:保留data.table行不在下一個會話
我有用戶填寫textInputs
在conditionalPanel
並單擊actionButton
另一個conditionalPanel,包括在data.table
的形式相同的信息後,出現。
我的問題似乎是rbind
函數結合assignment operator
。我不使用它,表格(Panel2)將僅包含Panel1的用戶輸入的第一行。如果我使用rbind,它會返回我預期的表(多個輸入行導致數據表中有多行)。
但關閉並重新啓動我的應用程序後,rbind正在將新輸入添加到舊的輸入。
比方說,我的第一個輸入將是:
A B C
關閉並重新啓動後,我輸入:
D E F
,其結果將是
A B C
D E F
但我只想:D E F
在我的表中。
請看看我的代碼:
library(shiny)
library(DT)
library(data.table)
ui = fluidPage(
conditionalPanel(
condition = "input.createTemplTable%2 == 0",
actionButton("add", "Add new Row", icon=icon("plus", class=NULL, lib="font-awesome")),
actionButton("remove", "Remove last Row", icon=icon("times", class = NULL, lib = "font-awesome")),
fluidRow(
column(2,
textInput("first", label = h5("first"))
),
column(2,
textInput("second", label = h5("second"))
),
column(2,
textInput("third", label = h5("third"))
)
),
tags$div(id = 'placeholder'),
actionButton("createTemplTable", "Create Template")
),
conditionalPanel(
condition = "input.createTemplTable%2 == 1",
#actionButton("return", "Return to Template Generator"),
dataTableOutput("createdTempl")
)
)
server = function(input, output) {
## keep track of elements inserted and not yet removed
inserted <- reactiveValues(val = 0)
tableColumns <- c("first", "second", "third")
observeEvent(input$add, {
id <- length(inserted$val) + 1
insertUI(
selector = "#placeholder",
where = "beforeBegin",
ui =tags$div(
id = id,
fluidRow(
column(2,
textInput("first", label = (""))
),
column(2,
textInput("second", label = (""))
),
column(2,
textInput("third", label = (""))
)
)
)
)
inserted$val <- c(inserted$val, id)
})
observeEvent(input$remove,{
print(inserted$val)
removeUI(
selector = paste0('#', inserted$val[length(inserted$val)])
)
inserted$val <- inserted$val[-length(inserted$val)]
})
saveData <- function(data) {
data <- as.data.table(t(data))
if (exists("createdTempl")) {
createdTempl <<- rbind(createdTempl, data)
} else {
createdTempl <<- data
}
}
loadData <- function() {
if (exists("createdTempl")) {
createdTempl
}
}
formData <- reactive({
data <- sapply(tableColumns, function(x) input[[x]])
data
})
observeEvent(input$createTemplTable, {
saveData(formData())
})
output$createdTempl <- renderDataTable({
input$createTemplTable
loadData()
})
}
shinyApp(ui = ui, server = server)
我需要使用會話?如果是的話,我會怎麼做? 謝謝!
這是發生,因爲變量'createdTempl'是跨會話共享的全局變量。您應該使用反應值。 – SBista
如何將表格作爲reactiveValue?沒有reactiveDataTable。對不起,我還是很新的閃亮。 – Rivka