如何在R Notebook中将Shiny应用内的clusters变量传递至后续代码块?
Got it, let's figure out how to make that clusters variable from your Shiny server accessible in later R Notebook code blocks—whether by writing/reading a CSV (your initial plan) or a couple of cleaner alternatives that might fit your workflow better.
This is a solid, reliable method especially if you want a persistent record of your clustering results, or if your Shiny app is running in a context where global environment access is tricky.
Step 1: Write clusters to CSV from the Shiny server
Inside your Shiny server function, right after you generate the kmeans clusters, write the relevant data to a CSV file. You can save just the cluster labels, or more details from the kmeans object—whatever you need later.
server <- function(input, output) { # Render your cluster plot (or other output) output$cluster_plot <- renderPlot({ # Replace with your actual data and clustering logic sample_data <- iris[, 1:4] clusters <- kmeans(sample_data, centers = input$num_clusters) # Write cluster labels to CSV (adjust path if needed) write.csv(clusters$cluster, file = "cluster_assignments.csv", row.names = FALSE) # Continue with your plot rendering plot(sample_data, col = clusters$cluster, pch = 16) }) }
Step 2: Read the CSV in a later Notebook code block
Once you've run the Shiny app and generated the clusters, you can read the CSV into a variable that's usable in subsequent code. Add a short delay if needed to make sure the file is fully written before reading:
# Optional: Wait a second to ensure Shiny has finished writing the file Sys.sleep(1) # Read the cluster assignments into a usable variable my_clusters <- read.csv("cluster_assignments.csv")[, 1] # Test it out head(my_clusters)
If your Shiny app is running in the same R session as your Notebook (which it should be by default), you can skip the file step entirely and assign the clusters directly to the global environment. This is faster and avoids file system overhead.
server <- function(input, output) { output$cluster_plot <- renderPlot({ sample_data <- iris[, 1:4] clusters <- kmeans(sample_data, centers = input$num_clusters) # Assign clusters to the global environment assign("global_clusters", clusters$cluster, envir = .GlobalEnv) plot(sample_data, col = clusters$cluster, pch = 16) }) }
Then, in any code block after running the Shiny app and triggering the clustering, you can just use global_clusters directly:
# Use the clusters from Shiny table(global_clusters)
- Check your working directory: Make sure both the Shiny app and your Notebook are using the same working directory (run
getwd()in both contexts to verify). This prevents "file not found" errors with the CSV method. - Save full kmeans objects if needed: If you want more than just cluster labels (like centroids, within-cluster sums of squares), use
saveRDS(clusters, "kmeans_results.rds")instead of CSV, then read it back withreadRDS("kmeans_results.rds"). RDS preserves the full structure of the kmeans object, which CSV can't do. - Timing matters: If you're running code automatically after the Shiny app, add a short
Sys.sleep()or usereactiveFileReader(for Shiny-driven updates) to ensure the data is ready before reading.
内容的提问来源于stack exchange,提问作者Jacek Kotowski

