title: Fastest way to coerce matrix to integer matrix in R
body: <p>I just realized that if you create a matrix with integer values, they are rather stored as numeric.</p>
  
  <pre><code>a &lt;- matrix(c(0,1,0,1), ncol=2)
  class(a[1,]) # numeric
  </code></pre>
  
  <p>a matrix of integers need half the amount of memory (for large dimensions).
  The following function coerces all values to integers:</p>
  
  <pre><code>forceMatrixToInteger &lt;- function(m){
      apply (m, c (1, 2), function (x) {
           (as.integer(x))
      })
  }
  
  a &lt;- forceMatrixToInteger(a)
  
  class(a[1,]) # integer
  </code></pre>
  
  <p>I wanted to know if you can think of any other way to do this, and if it would be faster or more memory efficient.</p>
  
  <p>sessionInfo</p>
  
  <pre><code>R version 3.2.3 (2015-12-10)
  Platform: x86_64-apple-darwin13.4.0 (64-bit)
  Running under: OS X 10.11.3 (El Capitan)
  </code></pre>
  
  <p>EDIT: First Test</p>
  
  <p>I defined a function that does what Richard Scriven answer describes, and the one I defined, and tested speed.</p>
  
  <pre><code>exp_size &lt;- 4
  exp_reps &lt;- 3 
  mat &lt;- matrix(sample(c(0,1), 10^exp_size, replace=TRUE),ncol=10^(exp_size/2))
  
  fun1&lt;-function(){
      mode(mat) &lt;- 'integer'
  }
  
  time &lt;- proc.time()
      for (i in 1:10^exp_reps){
      fun1()
  }
  time &lt;- proc.time()-time
  print('Results fun1:')
  print(time)
  
   print(time)
   # user  system elapsed 
   # 0.096   0.035   0.132 
  
  fun2 &lt;- function(){
      apply (mat, c (1, 2), function (x) {
           (as.integer(x))
      })
  }
  
  time &lt;- proc.time()
  for (i in 1:10^exp_reps){
      fun2()
  }
  time &lt;- proc.time()-time
  print('Results fun2:')
  print(time)
  
  # user  system elapsed 
  # 22.592   0.148  22.775 
  </code></pre>
  
  <p>There is a clear winner.</p>