title: Efficient way to create market basket matrix in R
body: <p>I am trying to create a market basket matrix from data that looks like the following:</p>
  
  <pre><code>input &lt;- matrix( c(1000001,1000001,1000001,1000001,1000001,1000001,1000002,1000002,1000002,1000003,1000003,1000003,100001,100002,100003,100004,100005,100006,100002,100003,100007,100002,100003,100008), ncol=2)
  </code></pre>
  
  <p>This represents the folowing data:</p>
  
  <pre><code>colnames(input) &lt;- c( "Customer" , "Product" )
  </code></pre>
  
  <p>From this a matrix is created which has a customer as a row and all the products as columns. This can be achieved by first creating this matrix with zero's:</p>
  
  <pre><code>input &lt;- as.data.frame(input)
  m &lt;- matrix(0, length(unique(input$Customer)), length(unique(input$Product)))
  rownames(m) &lt;- unique(input$Customer)
  colnames(m) &lt;- unique(input$Product)
  </code></pre>
  
  <p>This is all fast enough (have data of 750 000+ rows, creating a 15000 by 1500 matrix), but now I want to fill the matrix where appropriate:</p>
  
  <pre><code>for( i in 1:nrow(input) ) {
      m[ as.character(input[i,1]),as.character(input[i,2])] &lt;- 1
  }
  </code></pre>
  
  <p>I think there has to be a more efficient way to do this, as I learned from stackoverflow that for loops can often be avoided. So the question is, is there a faster way?</p>
  
  <p>And i need the data in a matrix because i would like to use packages like caret. And after that i will be probably running into the same problem  as here <a href="https://stackoverflow.com/questions/6449588/r-memory-management-advice-caret-model-matrices-data-frames">R memory management advice (caret, model matrices, data frames)</a>, but that's a concern for later.</p>