Reputation: 23
in my Shiny app I want to save the content of the input fields as a new row in a dataframe with an action button. I created an empty dataframe outside of the server function and wanted to add the content via rbind. This also works great in R, but obviously not in Shiny. What is my misconception? Here is a simplified example with one field
library(shiny)
#create an empty dataframe
df <- data.frame(name = character(), stringsAsFactors = FALSE)
ui <- fluidPage(
textInput("name", "Enter Name"),
actionButton("add", "Add Data to table"),
tableOutput ("result")
)
server <- function(input, output) {
data <- reactive (data.frame(name = input$name))
#add data to df
observeEvent(input$add, {
df <- rbind(df,data())
})
output$result <- renderTable(df)
}
shinyApp(ui, server)
Upvotes: 0
Views: 623
Reputation: 29417
You can use reactiveVal
to update the data. This will be unique for each session, if you want to append to dataframe globally use <<-
library(shiny)
#create an empty dataframe
df <- data.frame(name = character(), stringsAsFactors = FALSE)
ui <- fluidPage(
textInput("name", "Enter Name"),
actionButton("add", "Add Data to table"),
tableOutput ("result")
)
server <- function(input, output) {
df_server <- reactiveVal(df)
data <- reactive({
req(input$name)
data.frame(name = input$name)
})
#add data to df
observeEvent(input$add, {
temp_df <- rbind(df_server(),data())
df_server(temp_df)
})
output$result <- renderTable(df_server())
}
shinyApp(ui, server)
Upvotes: 1