You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Shiny Google表单优化需求:数值排序、ID显示及Shiny后代码执行

Hey Bruno, let’s tackle your Shiny app challenges one by one—here are practical, actionable solutions for each of your requirements:


1. Sorting Numeric Inputs

Let’s assume you have a set of numeric inputs (e.g., input$score1, input$score2, input$score3) that you want to sort. You can use a reactive expression to collect, clean, and sort these values dynamically:

# Reactive expression to handle sorted numeric inputs
sorted_scores <- reactive({
  # Gather all numeric input values
  raw_scores <- c(input$score1, input$score2, input$score3)
  # Remove any missing values (NA)
  clean_scores <- raw_scores[!is.na(raw_scores)]
  # Sort in ascending order (use decreasing = TRUE for descending)
  sort(clean_scores)
})

# Display sorted values in your UI
output$sorted_scores_output <- renderPrint({
  cat("Sorted numeric values:", paste(sorted_scores(), collapse = ", "))
})

If your numeric inputs are dynamically generated (e.g., via renderUI), adjust the reactive to loop through all input IDs matching your pattern (e.g., paste0("score", 1:5)).


2. Display the Last Entry by ID After Saving Data

First, ensure your dataset includes an auto-incrementing ID column (or use row names as IDs). When the user saves their data, you can capture the latest entry and display it immediately:

# Reactive value to store all user submissions
submissions <- reactiveVal(data.frame(
  id = integer(),
  numeric_val = numeric(),
  text_val = character(),
  stringsAsFactors = FALSE
))

# Observer for the save button
observeEvent(input$save_button, {
  # Create new entry with auto-incremented ID
  new_entry <- data.frame(
    id = nrow(submissions()) + 1,
    numeric_val = input$numeric_input,
    text_val = input$text_input
  )
  
  # Update the submissions dataset
  updated_submissions <- rbind(submissions(), new_entry)
  submissions(updated_submissions)
  
  # Save to a CSV file
  write.csv(updated_submissions, "user_submissions.csv", row.names = FALSE)
  
  # Fetch and display the last entry by ID
  last_entry <- updated_submissions[updated_submissions$id == max(updated_submissions$id), ]
  output$last_entry_display <- renderTable({
    last_entry
  }, caption = "Last Saved Entry")
})

If you’re using row names as IDs instead, replace updated_submissions$id with rownames(updated_submissions) and adjust the max logic to max(as.integer(rownames(updated_submissions))).


3. Run Code After Shiny App Closes

To execute server-side code when the user closes the browser tab or terminates the session, use session$onSessionEnded(). This triggers code once the session is fully closed:

server <- function(input, output, session) {
  # Your existing server logic here...
  
  # Code to run after the session ends
  session$onSessionEnded(function() {
    # Example: Create a backup of submissions
    if (file.exists("user_submissions.csv")) {
      file.copy(
        from = "user_submissions.csv",
        to = paste0("submissions_backup_", Sys.Date(), ".csv"),
        overwrite = TRUE
      )
      cat("Session ended: Backup created successfully.\n")
    }
    
    # Other tasks: Clean temporary files, send email alerts, etc.
  })
}

Note: This runs on the server side—if you need client-side browser actions on close, you’d use custom JavaScript, but for server tasks like backups or cleanup, this is the standard approach.


And if you need help translating any Portuguese parts of your form into English for broader support, feel free to share the text—I’d be happy to assist with that too!

内容的提问来源于stack exchange,提问作者Bruno

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 09:37:45