我正在尝试在我的Shiny应用程序中输出一个表,每次单击“提交”按钮时都会添加其他行。但是,它不是累积行,而是替换第一行。 Shiny文档对我没什么帮助(尽管它非常好)。
以下是用户界面:
shinyUI(fluidPage(
titlePanel("CSF Payroll App"),
sidebarLayout(
sidebarPanel(
textInput("name", "Put your name here"),
textInput("job", "Job completed"),
dateInput("date", "Input the date you worked"),
numericInput("minutes", "Input the time you worked
(15 minute increments)", 0,0,240,15),
submitButton("Submit")
),
mainPanel(
tableOutput("totalHours")
)
)
))
这是服务器:
shinyServer(function(input, output) {
# Initialize a dataframe to hold all entries.
totalFrame <- data.frame(
Name <- character(),
Job <- character(),
Date <- character(),
Minutes <- numeric(),
stringsAsFactors=FALSE)
colnames(totalFrame) <- c("Name", "Job",
"Date", "Minutes")
# Create a temporary dataframe to take a new entry, reactively,
# then update the totalFrame with each new entry.
addNextEntry <- reactive({
Name <- input$name
Job <- input$job
Date <- as.character(input$date)
Minutes <- input$minutes
tempFrame <- data.frame(Name, Job, Date, Minutes)
totalFrame <- bind_rows(totalFrame, tempFrame)
totalFrame
})
# Update the summary dataframe with new entries as they come in.
output$totalHours <- renderTable({
addNextEntry()
})
})
如何以一种获取被动内容的方式更新totalFrame,但是在totalFrame中累积而不是一次又一次地替换第一行?
示例输出: 如果我将(“Bob”,“Cleans”,2017-04-25,30)放入框架的相应列中,它会正确呈现表格,但如果我尝试添加另一个条目,它只会替换Bob Cleans行。
答案 0 :(得分:1)
<强>解决方案强>
使用
reactiveValues
生成默认和反应表,并结合observeEvent
检查按钮是否按下,submitButton
更改为actionButton
。这会更新初始表(正如HubertL提到的那样)。
<强>代码强>
library(shiny)
library(dplyr)
ui <- shinyUI(fluidPage(
titlePanel("CSF Payroll App"),
sidebarLayout(
sidebarPanel(
textInput("name", "Put your name here"),
textInput("job", "Job completed"),
dateInput("date", "Input the date you worked"),
numericInput("minutes", "Input the time you worked
(15 minute increments)", 0,0,240,15),
actionButton(inputId = 'button_1',label = 'Add')
),
mainPanel(
tableOutput("totalHours")
)
)
))
server <- function(input, output) {
# default table
totalFrame <- reactiveValues(table = data.frame(
Name = character(),
Job = character(),
Date = character(),
Minutes = numeric(),
stringsAsFactors = FALSE))
# update default table, when actionButton is pressed
observeEvent(input$button_1, {
totalFrame$table <- bind_rows(
totalFrame$table,
data.frame(
Name = input$name,
Job = input$job,
Date = as.character(input$date),
Minutes = input$minutes
)
)
})
table <- reactive({totalFrame$table})
# just render the table
output$totalHours <- renderTable({
table()
})
}
shinyApp(ui = ui, server = server)
<强>输出强>
之前的
之后(按5x)