title: Optimizing K-means clustering using Genetic Algorithm
body: <p>I have the following <code>dataset</code> (obtained <a href="https://www.r-bloggers.com/genetic-algorithms-a-simple-r-example/" rel="nofollow noreferrer">here</a>):</p>
  
  <pre><code>----------item survivalpoints weight
  1  pocketknife             10      1
  2        beans             20      5
  3     potatoes             15     10
  4       unions              2      1
  5 sleeping bag             30      7
  6         rope             10      5
  7      compass             30      1
  </code></pre>
  
  <p>I  can cluster this dataset into three clusters with <code>kmeans()</code> using a binary string as my initial choice of centers. For eg:</p>
  
  <pre><code>## 1 represents the initial centers
  chromosome = c(1,1,1,0,0,0,0)
  ## exclude first column (kmeans only support continous data)
  cl &lt;- kmeans(dataset[, -1], dataset[chromosome == 1, -1])
  ## check the memberships
  cl$clusters
  # [1] 1 3 3 1 2 1 2
  </code></pre>
  
  <p>Using this fundamental concept, I tried it out with <code>GA</code> package to conduct the search where I am trying to optimize(minimize) Davies-Bouldin (DB) Index.</p>
  
  <pre><code>library(GA)           ## for ga() function
  library(clusterSim)   ## for index.DB() function
  
  ## defining my fitness function (Davies-Bouldin)
  DBI &lt;- function(x) {
          ## converting matrix to vector to access each row
          binary_rep &lt;- split(x, row(x))
          ## evaluate the fitness of each chromsome
          for(each in 1:nrow(x){
              cl &lt;- kmeans(dataset, dataset[binary_rep[[each]] == 1, -1])
              dbi &lt;- index.DB(dataset, cl$cluster, centrotypes = "centroids")
              ## minimizing db
              return(-dbi)
      }
  }
  
  g&lt;- ga(type = "binary", fitness = DBI, popSize = 100, nBits = nrow(dataset))
  </code></pre>
  
  <p>Of course (I have no idea what's happening), I received error message of 
  <code>Warning messages:
  Error in row(x) : a matrix-like object is required as argument to 'row'</code></p>
  
  <p>Here are my questions:</p>
  
  <ol>
  <li>How can correctly use the <code>GA</code> package to solve my problem?</li>
  <li>How can I make sure the randomly generated chromosomes contains the same number of <code>1</code>s which corresponds to <code>k</code> number of clusters (eg. if <code>k=3</code> then the chromosome must contain exactly three <code>1</code>s)?</li>
  </ol>