如何允许selectizeInput允许用户输入新条目以及加载一些旧条目

时间:2019-11-23 09:04:47

标签: r shiny

我正在尝试使用持久性数据存储来允许用户将先前输入的文本数据加载到文本框中。我还希望用户能够输入一些新数据并将其存储。该应用程序可以运行,但不允许用户在文本框中输入新数据。我尝试将selectizeInput与create = TRUE选项一起使用,但没有成功。这是我的代码:

library(shiny)
library(here)


outputDir <- here("responses")

saveData <- function(data) {
  data <- t(data)
  # Create a unique file name
  fileName <- sprintf("%s_%s.csv", as.integer(Sys.time()), digest::digest(data))
  # Write the file to the local system
  write.csv(
    x = data,
    file = file.path(outputDir, fileName), 
    row.names = FALSE, quote = TRUE
  )
}

loadData <- function() {
  # Read all the files into a list
  files <- list.files(outputDir, full.names = TRUE)
  data <- lapply(files, read.csv, stringsAsFactors = FALSE) 
  # Concatenate all data together into one data.frame
  data <- do.call(rbind, data)
  data
}

# Define the fields we want to save from the form
fields <- c("name", "used_shiny", "r_num_years")

# Shiny app with 3 fields that the user can submit data for
shinyApp(
  ui = fluidPage(
    DT::dataTableOutput("responses", width = 300), tags$hr(),
    selectizeInput("MyChoices","Select from ui delimiters", choices=
                     loadData()[,1],options = list(create = TRUE)),
    checkboxInput("used_shiny", "I've built a Shiny app in R before", FALSE),
    sliderInput("r_num_years", "Number of years using R",
                0, 25, 2, ticks = FALSE),
    actionButton("submit", "Submit")
  ),
  server = function(input, output, session) {

    # Whenever a field is filled, aggregate all form data
    formData <- reactive({
      data <- sapply(fields, function(x) input[[x]])
      data
    })

    # When the Submit button is clicked, save the form data
    observeEvent(input$submit, {
      saveData(formData())
    })

    # Show the previous responses
    # (update with current response when Submit is clicked)
    output$responses <- DT::renderDataTable({
      input$submit
      loadData()
    }) 


  }
)

1 个答案:

答案 0 :(得分:1)

哈哈,这是一个简单的答案。如果要加载存储的条目并允许输入新条目,则必须允许多个= TRUE。以下内容需要作为ui的一部分添加:

selectizeInput("name", "Name", "",multiple = TRUE,options = list(create = TRUE),choices=loadData()[,1])