title: using kmeans within an apply function in r
body: <p>i am facing a new challenge today! I would like to perform a kmeans on each line of my table separately (in my case this represents monthly weather data)   get a table for each point and month with cluster number. </p>
  
  <h2>The illustration</h2>
  
  <h3>here is an extract of the data (i have about 1700 observations in total showing only 10 here)</h3>
  
  <pre><code>data&lt;-c( 
   245,      84 ,     99 ,  161,   249, 190 , 136 , 122 ,   157,       128  ,   123 ,     138 ,     106,
   246,      84 ,    101,   163 ,  257, 194 , 138 , 126 ,   163,       134  ,   127 ,     142 ,     108,
   247,     60  ,    80  , 131,   191, 156 ,  90  , 82  ,  106 ,       85  ,    86 ,     106  ,     88,
   248,      60 ,     80  , 131 ,  191, 156,   90 ,  82,    106 ,       85 ,     86 ,     106  ,     88,
   249 ,     60 ,     80 ,  131,   191, 156,   90,   82,    106 ,       85 ,     86 ,     106  ,     88,
   250 ,     58 ,     79 ,  131,   197, 156,   90,   78,    101 ,       84 ,     84 ,     106  ,     88,
   251 ,     60 ,     81 ,  135,   210, 163,   91,   82,    107 ,       88 ,     89 ,     108  ,     89,
   252 ,     67 ,     86 ,  140,   214, 168,  105,   92,    121 ,       99 ,     99 ,     114 ,      93,
   253,      70 ,     89 ,  144,   225, 171 , 110,   97,    128 ,      105 ,    104 ,     118 ,      94,
   254,      70 ,     89 ,  144,   225, 171,  110,   97,    128 ,      105 ,    104 ,     118 ,      94,
   255,      62 ,     82,   134,   205, 163 ,  94,   85,    110 ,       88 ,     90,      109,       89)
  data&lt;-matrix(data, nrow=10,ncol=13,byrow=FALSE) 
  data&lt;-data.frame(data)
  names(data)&lt;-c('ID' ,'January' ,'Febuary', 'March', 'April', 'May' ,'June' ,'July' ,'August' ,'September' ,'October', 'November', 'December')
  </code></pre>
  
  <h3>performing a kmeans classification on each observation line</h3>
  
  <p>as you see i work with 2 clusters </p>
  
  <pre><code>kmean&lt;-apply(data[,2:13], 1,  function(x) {kmeans(x, 2)})
  </code></pre>
  
  <p>Great this works, and creates a list with the kmeans reports (that are also list,of which the second one is the cluster number)</p>
  
  <p>i can look at the cluster numbers for a specific line, say line 2 like this </p>
  
  <pre><code>kmean[[2]]$cluster
  </code></pre>
  
  <h3>the challenge</h3>
  
  <p>now i would like to get a table that gives me the result of kmean$cluster for each observation in my dataframe. </p>
  
  <p>So i tried the following : </p>
  
  <pre><code>cluster&lt;-apply(kmean, 1, function (y) {kmean[[y]]$cluster})
  </code></pre>
  
  <p>But then i get the following error : 
  <em>Error in apply(kmean, 1, function(y) { : 
    dim(X) must have a positive length</em> </p>
  
  <p>Any suggestion how i can get my table showing for each line and each month to which cluster the observation belongs to? </p>
  
  <p>A great thanks for looking at this! Catherine </p>