如何在 r shiny 中过滤列和拟合模型

How to filter columns and fit models in rshiny

我想将几种聚类算法拟合到我的数据集,仅包含 selected 列。请在下面找到我的试用版:

    library(rshiny)
    data(mtcars)
      if (interactive()) {
  shinyApp(
    ui = fluidPage(
      sliderInput('num',label='Insert Number of clusters',value = 3,min = 2,max = 10,step = 1),
      varSelectInput("variables", "Variables:", mtcars, multiple = TRUE),
      selectInput('Model','Model:',choices = c('K-Means','Others')),
      tableOutput("data")
    ),
    server = function(input, output) {
      output$data <- renderTable({
        if (length(input$variables) == 0) return(mtcars)
        mtcars %>% dplyr::select(!!!input$variables)
        if (input$Model == 'K-means'){
          autoplot(kmeans(df_clean,input$num),data=df_clean,label=TRUE,label.size=3)
        }
      }, rownames = TRUE)
    }
  )}

这使我能够 select 适合的列和模型类型,但我无法在仪表板上看到聚类算法。

如有任何帮助,我们将不胜感激。

您需要分离不同种类的输出。您不能在同一输出中有 table 输出和绘图。 我举了一个例子,它如何与情节的 conditinalPanel 一起工作

library(rshiny)
data(mtcars)
if (interactive()) {
  shinyApp(
    ui = fluidPage(
      sliderInput('num',label='Insert Number of clusters',value = 3,min = 2,max = 10,step = 1),
      varSelectInput("variables", "Variables:", mtcars, multiple = TRUE),
      selectInput('Model','Model:',choices = c('K-Means','Others')),
      column(
        width = 4,
        tableOutput("data")
      ),
      column(
        width = 6,
        conditionalPanel(
          condition = "input.Model == 'K-Means'",
          plotOutput("cluster")
        )
      )
    ),
    server = function(input, output) {
      
      df_clean <- reactive({
        if (length(input$variables) == 0) return(mtcars)
        mtcars %>% 
          dplyr::select(!!!input$variables)
      })
      
      output$data <- renderTable({
        df_clean()
      }, rownames = TRUE)
      output$cluster <- renderPlot({
        req(input$Model == 'K-Means')
        
        axises <- unlist(c(input$variables,"mpg", "cyl"))[1:2]
        cluster <- kmeans(df_clean(),input$num)
        ggplot(df_clean(), aes_string(x = axises[[1]],y = axises[[2]] )) +
          geom_point(colour = cluster$cluster)
      })
    }
  )}