|
| 1 | +library(shiny) |
| 2 | + |
| 3 | +.parameters <- setdiff(names(iris), "Species") |
| 4 | + |
| 5 | +kmean_cluster_tab <- tabPanel("K-Mean Clustering", pageWithSidebar( |
| 6 | + headerPanel("Iris k-means clustering"), |
| 7 | + sidebarPanel( |
| 8 | + selectInput("xcol", "X Variable", .parameters), |
| 9 | + selectInput("ycol", "Y Variable", .parameters, selected = .parameters[[2]]), |
| 10 | + numericInput("clusters", "Cluster count", 3, min = 1, max = 9) |
| 11 | + ), |
| 12 | + mainPanel( |
| 13 | + plotOutput("plot1") |
| 14 | + ) |
| 15 | +)) |
| 16 | + |
| 17 | +kmean_cluster_server <- function(input, output, session) { |
| 18 | + # Combine the selected variables into a new data frame |
| 19 | + selected_data <- reactive({ |
| 20 | + iris[, c(input$xcol, input$ycol)] |
| 21 | + }) |
| 22 | + |
| 23 | + clusters <- reactive({ |
| 24 | + kmeans(selected_data(), input$clusters) |
| 25 | + }) |
| 26 | + |
| 27 | + output$plot1 <- renderPlot({ |
| 28 | + palette(c( |
| 29 | + "#E41A1C", "#377EB8", "#4DAF4A", "#984EA3", |
| 30 | + "#FF7F00", "#FFFF33", "#A65628", "#F781BF", "#999999" |
| 31 | + )) |
| 32 | + |
| 33 | + par(mar = c(5.1, 4.1, 0, 1)) |
| 34 | + plot(selected_data(), |
| 35 | + col = clusters()$cluster, |
| 36 | + pch = 20, cex = 3 |
| 37 | + ) |
| 38 | + points(clusters()$centers, pch = 4, cex = 4, lwd = 4) |
| 39 | + }) |
| 40 | +} |
0 commit comments