[英]How to isolate the output of a reactive (function) and save to a data.frame?
這是對上一個問題的補充 : 在Shiny中將值添加到反應表
也許這是一個菜鳥問題,但值得一試。 這是我的第一個Shiny應用程序。
我正在制作一個Shiny應用程序,它將允許用戶將其輸入和從其輸入計算出的值存儲到data.frame。 這樣他們就可以比較輸出中的值。 我已經在我的代碼中模擬了要存儲3列的地方:輸入A和B,以及基於輸入A和B的函數。
我認為我無法理解評估反應性是我的缺點,因此我向社區尋求幫助。 如果我只存儲輸入而不是反應函數'calcAB()',則可以使代碼工作。 一旦包含該功能,一切都會崩潰。 我收到一個錯誤:
Warning: Error in [<-.data.frame: replacement has 2 items, need 3
如果刪除calcAB()函數,則可以毫無問題地保存輸入。 一旦包含它,就會出現上述錯誤。 問題是如何將反應功能的輸出存儲在data.frame中?
我的代碼如下:
用戶界面代碼:
shinyUI(fluidPage(
# Application title
titlePanel("Test Save Data to DF"),
# Sidebar with inputs A and B
sidebarLayout(
sidebarPanel(
sliderInput("A",
"Input A",
min = 1,
max = 50,
value = 30),
numericInput("B",
"Input B",
min = 1,
max = 30,
value = 10),
# Action Button to save the inputs to a data.frame
actionButton('update', label = 'Update')
),
mainPanel(
tableOutput('testTable')
)
)
))
服務器代碼:
shinyServer(function(input, output) {
# My reactive function
calcAB <- reactive({
input$A * input$B
})
values <- reactiveValues()
values$df <- data.frame('A' = numeric(0), 'B' = numeric(0),
'AB' = numeric(0))
newEntry <- observe({
if(input$update >0) {
newLine <- isolate(c(input$A, input$B, calcAB()))
isolate(values$df[nrow(values$df)+1,] <- c(input$A, input$B, calcAB()))
})
output$testTable <- renderTable({values$df})
}
嘗試使用以下代碼:
shinyServer(function(input, output) {
calcAB <- reactive(input$A * input$B)
values <- reactiveValues(df = data.frame('A' = numeric(0), 'B' = numeric(0), 'AB' = numeric(0)))
newEntry <- observe({
if(input$update >0) {
values$df <- isolate(rbind(values$df,data.frame('A' =input$A, 'B' = input$B,'AB' = calcAB())))
}})
output$testTable <- renderTable({values$df})
})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.