title: Build Matrix depending on different conditions in a vector
body: <p>Please I need your help! I have a matrix like this</p>
  
  <pre><code>       A   B   C
   [1,] 101 201 301
   [2,] 102 202 302
   [3,] 103 203 303
   [4,] 104 204 304
   [5,] 105 205 305
   [6,] 106 206 306
   [7,] 107 207 307
   [8,] 108 208 308
   [9,] 109 209 309
  [10,] 110 210 310
  </code></pre>
  
  <p>and a vector with different values like this:
  categories &lt;- c("A","B","A","C","A","C","B")</p>
  
  <p>In the result I want to create the following matrix in R:</p>
  
  <pre><code>     A   B   A   C   A   C   B
  1  101 201 101 301 101 301 201
  2  102 202 102 302 102 302 202
  3  103 203 103 303 103 303 203
  4  104 204 104 304 104 304 204
  5  105 205 105 305 105 305 205
  6  106 206 106 306 106 306 206
  7  107 207 107 307 107 307 207
  8  108 208 108 308 108 308 208
  9  109 209 109 309 109 309 209
  10 110 210 110 310 110 310 210
  </code></pre>
  
  <p>Unfortunately, I'm just a beginner in R and so I have developed the following procedure:</p>
  
  <pre><code>#Create Example Data
  A &lt;- seq(101,110,1)
  B &lt;- seq(201,210,1)
  C &lt;- seq(301,310,1)
  rawdata.m &lt;- matrix(nrow=10,ncol=3,data=c(A,B,C))
  colnames(rawdata.m) &lt;- c("A","B","C")
  
  categories &lt;- c("A","B","A","C","A","C","B")
  
  #build new matrix dependent on vector
  if (categories[1]=="A") result.m &lt;- data.frame(rawdata.m[,1])
  if (categories[1]=="B") result.m &lt;- data.frame(rawdata.m[,2])
  if (categories[1]=="C") result.m &lt;- data.frame(rawdata.m[,3])
  
  for(i in 2:length(categories))
  {
    if (categories[i]=="A") result.m &lt;- data.frame(result.m, rawdata.m[,1])
    if (categories[i]=="B") result.m &lt;- data.frame(result.m, rawdata.m[,2])
    if (categories[i]=="C") result.m &lt;- data.frame(result.m, rawdata.m[,3])
  }
  colnames(result.m) &lt;- categories
  
  print(result.m)
  </code></pre>
  
  <p>This procedure does not look very elegant and is not fast if you use larger matrices. Do you know a better procedure?</p>
  
  <p>Thank You!</p>