Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
672 views
in Technique[技术] by (71.8m points)

r - Add values to a reactive table in shiny

I want users of my shiny app to be able to add elements to a table iteratively, but I can't work out how to hold the values.

In this example, I want the user to be able to add values in the text boxes, which should get added to the bottom of the table in the main panel. At the moment the previously added values are lost.

library(shiny)

runApp(list(
  ui=pageWithSidebar(headerPanel("Adding entries to table"),
                     sidebarPanel(textInput("text1", "Column 1"),
                                  textInput("text2", "Column 2"),
                                  actionButton("update", "Update Table")),
                     mainPanel(tableOutput("table1"))),
  server=function(input, output, session) {
    tableStart <- data.frame(Column1 = NA, Column2 = NA)
    newEntry <- reactive({
      input$update
      newLine <- isolate(c(input$text1, input$text2))
      })
    output$table1 <- renderTable({rbind(tableStart, newEntry())})
  }))
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I think you want to use reactiveValues() to store your data frame. Here is a possible solution:

library(shiny)

runApp(list(
  ui=pageWithSidebar(headerPanel("Adding entries to table"),
                 sidebarPanel(textInput("text1", "Column 1"),
                              textInput("text2", "Column 2"),
                              actionButton("update", "Update Table")),
                 mainPanel(tableOutput("table1"))),
server=function(input, output, session) {
values <- reactiveValues()
values$df <- data.frame(Column1 = NA, Column2 = NA)
newEntry <- observe({
  if(input$update > 0) {
    newLine <- isolate(c(input$text1, input$text2))
    isolate(values$df <- rbind(values$df, newLine))
  }
})
output$table1 <- renderTable({values$df})
}))

Edit

To avoid creating an empty row, create an empty data.frame rather than one with NA:

values$df <- data.frame(Column1 = numeric(0), Column2 = numeric(0))

And indexing seems better for adding the rows than rbind() (which messes up the column names... not sure why):

isolate(values$df[nrow(values$df) + 1,] <- c(input$text1, input$text2))

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...