user86907
user86907

Reputation: 837

How to filter columns and fit models in rshiny

I want to fit several clustering algorithms to my data set with the selected columns only. Please find my trial below:

    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)
    }
  )}

This enables me to select the columns and type of models to fit, but i am not able to see the clustering algorithm on the dashboard.

Any help with this would be apprecated.

Upvotes: 0

Views: 126

Answers (1)

Bertil Baron
Bertil Baron

Reputation: 5003

You need to separate different sorts of outputs. You can't have a table output and a plot in the same output. I made an example how it could work with a conditinalPanel for the plot

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)
      })
    }
  )}

Upvotes: 1

Related Questions