K-means clustering example using iris data from CSV file

823 views
Skip to first unread message

Guilherme Moraes Ferraudo

unread,
Jul 27, 2016, 8:50:42 PM7/27/16
to Shiny - Web Framework for R
Hello,

Please, how could be implemented the K-means clustering example (original is available on link below) using iris data from CSV file uploaded by user instead of iris data available on R?

Iris k-means clustering



Thanks in advance.

Guilherme


Tareef Kawaf

unread,
Jul 28, 2016, 7:29:22 AM7/28/16
to Shiny - Web Framework for R
Guilherme,
You may find this example on the shiny.rstudio.com website helpful on how to handle uploads from end users. 
Best,
Tareef

Guilherme Moraes Ferraudo

unread,
Jul 28, 2016, 7:44:21 AM7/28/16
to Tareef Kawaf, Shiny - Web Framework for R
Hi Tareef,

Thanks for reply.

I've read this example and implemented it with some differences. But when I run my app the following error message shows up on my screen:

ERROR: object 'dataframe' not found

What is wrong?

Below my current code:

server.r file

palette(c("#E41A1C", "#377EB8", "#4DAF4A", "#984EA3",
          "#FF7F00", "#FFFF33", "#A65628", "#F781BF", "#999999"))

shinyServer(function(input, output, session) {
  
  # The selected file, if any
  userFile <- reactive({
    # If no file is selected, don't do anything
    validate(need(input$file, message = FALSE))
    input$file
  })
  
  # The user's data, parsed into a data frame
  dataframe <- reactive({
    read.csv(userFile()$datapath,
             header = input$header,
             sep =    input$sep,
             quote = input$quote)
  })
  
  output$contents = renderTable({dataframe()})
  
  # Combine the selected variables into a new data frame
  selectedData <- reactive({
    filedata()[, c(input$xcol, input$ycol)]
  })
  
  clusters <- reactive({
    kmeans(selectedData(), input$clusters)
  })
  
  output$kmeansPlot <- renderPlot({
    par(mar = c(5.1, 4.1, 0, 1))
    plot(selectedData(),
         col = clusters()$cluster,
         pch = 20, cex = 3)
    points(clusters()$centers, pch = 4, cex = 4, lwd = 4)
  })
  return(dataframe)
})

ui.r file

shinyUI(
        navbarPage("", inverse = TRUE,
                   tabPanel("Prof. Antonio Sergio Ferraudo - Multivariate analysis"),
                            tabPanel("Cluster",
                                    mainPanel(tabsetPanel(type = "tabs",
                                    #Page showing data importing table                     
                                              tabPanel("Data table", 
                                                        sidebarPanel(width = 2,
                                                                      fileInput('file', 'Choose CSV File',
                                                                      accept=c('text/csv', 
                                                                      'text/comma-separated-values,text/plain', 
                                                                      '.csv')),
                                                                                tags$hr(),
                                                                      checkboxInput('header', 'Header', TRUE),
                                                                      radioButtons('sep', 'Separator',
                                                                                  c(Comma=',',
                                                                                  Semicolon=';',
                                                                                  Tab='\t'),
                                                                                  ','),
                                                                     radioButtons('quote', 'Quote',
                                                                                  c(None='',
                                                                                  'Double Quote'='"',
                                                                                  'Single Quote'="'"),
                                                                                  '"')
                                                                    ),
                                                                      tableOutput('contents')), 
                                              tabPanel("K-means clustering", 
                                                       headerPanel('k-means clustering'),
                                                                   sidebarPanel(width =2,
                                                                                selectInput('xcol', 'X Variable', choices = colnames(dataframe)),
                                                                                selectInput('ycol', 'Y Variable', choices = colnames(dataframe), selected = colnames(dataframe)[2]),
                                                                                               numericInput('clusters', 'Cluster count', 3, min = 1, max = 9)
                                                                               ),
                                                                      plotOutput('kmeansPlot')) 
                                                              ) #end of tabsetPanel
                                                  ) #end of mainPanel
                                      ), #end of tabPanel,
                   tabPanel("Principal component"),
                   navbarMenu("Coming up",
                              tabPanel("Correspondence"),
                              tabPanel("Discriminant"),
                              tabPanel("Factors")
                              )
                  )
)

Thanks again.


--
You received this message because you are subscribed to a topic in the Google Groups "Shiny - Web Framework for R" group.
To unsubscribe from this topic, visit https://groups.google.com/d/topic/shiny-discuss/_Ftr0j-d-Lc/unsubscribe.
To unsubscribe from this group and all its topics, send an email to shiny-discus...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/shiny-discuss/f7be029f-e294-4e6e-9ffb-d104e43a6219%40googlegroups.com.

For more options, visit https://groups.google.com/d/optout.



--
Guilherme Moraes Ferraudo
São Paulo - SP

Tareef Kawaf

unread,
Jul 28, 2016, 7:47:39 AM7/28/16
to Guilherme Moraes Ferraudo, Shiny - Web Framework for R
I am not as facile with shiny as others on this list, but from looking at the error, it looks like your return(dataframe) might want to be return(dataframe()) since dataframe is defined as a reactive.


Guilherme Moraes Ferraudo

unread,
Jul 28, 2016, 7:49:57 AM7/28/16
to Tareef Kawaf, Shiny - Web Framework for R
Hi Tareef,

I've implemented your suggestion and take a look at the new error message:

ERROR: object 'dataframe' not found


Thanks!
 

Tareef Kawaf

unread,
Jul 28, 2016, 8:47:37 AM7/28/16
to Guilherme Moraes Ferraudo, Shiny - Web Framework for R
Hi Guilherme,
I didn't pay as much attention in the first look at your code, but shiny is complaining because you are referencing dataframe and dataframe hasn't been loaded yet.  dataframe will get loaded when an upload occurs, so you wouldn't be able to have the UI show the column names of a data frame that doesn't exist yet.  

I am not sure what the best pattern to follow would be here, but if I had to guess I would look at this article on building dynamic UIs and have that part of the UI show up once the user has selected the csv file to upload.

HTH

Guilherme Moraes Ferraudo

unread,
Jul 28, 2016, 5:36:24 PM7/28/16
to Tareef Kawaf, Shiny - Web Framework for R
Tareef,

I did your recommendation following the article: http://shiny.rstudio.com/articles/dynamic-ui.html

But I could not achieve my goal. Please, follows below my script:


server.r file
palette(c("#E41A1C", "#377EB8", "#4DAF4A", "#984EA3",
          "#FF7F00", "#FFFF33", "#A65628", "#F781BF", "#999999"))

shinyServer(function(input, output, session) {
  
  # The selected file, if any
  userFile <- reactive({
    # If no file is selected, don't do anything
    validate(need(input$file, message = FALSE))
    input$file
  })
  
  # The user's data, parsed into a data frame
  dataframe <- reactive({
    read.csv(userFile()$datapath,
             header = input$header,
             sep =    input$sep,
             quote = input$quote)
  })
  
  output$contents = renderTable({dataframe()})
  
  # Partial example
  output$colNames <- renderUI({
    colnamesDf = colnames(dataframe())
    checkboxGroupInput(input$xcol, 'X Variable', choices = colnamesDf)
    numericInput('clusters', 'Cluster count', 3, min = 1, max = 9)
  })
  
  # Combine the selected variables into a new data frame
  selectedData <- reactive({
    dataframe()[, c(input$xcol, input$ycol)]
  })
  
  clusters <- reactive({
    kmeans(selectedData(), input$clusters)
  })
  
  output$kmeansPlot <- renderPlot({
    par(mar = c(5.1, 4.1, 0, 1))
    plot(selectedData(),
         col = clusters()$cluster,
         pch = 20, cex = 3)
    points(clusters()$centers, pch = 4, cex = 4, lwd = 4)
  })
  
  
})

ui.r file
                                                                                #uiOutput('colNames'),
                                                                                #selectInput('xcol', 'X Variable', choices = list()),
                                                                                #selectInput('ycol', 'Y Variable', choices = list(),),
                                                                                uiOutput('colNames')
                                                                                       ),
                                                                      plotOutput('kmeansPlot')) 
                                                              ) #end of tabsetPanel
                                                  ) #end of mainPanel
                                      ), #end of tabPanel,
                   tabPanel("Principal component"),
                   navbarMenu("Coming up",
                              tabPanel("Correspondence"),
                              tabPanel("Discriminant"),
                              tabPanel("Factors")
                              )
                  )
)



Thanks in advance

Best
Reply all
Reply to author
Forward
0 new messages