title: R: put results of function in corresponding original position of inputs after a subset
body: <p>Suppose I have two matrices <code>mat</code> and <code>obj</code>:</p>
  
  <pre><code>time &lt;- c(1, 1, 2, 2, 3, 3)
  money &lt;- c(2, 2, 4, 4, 6, 6)
  ownership &lt;- c(1, 0, 1, 0, 1, 0)
  randomstuff &lt;- matrix(runif(18),nrow = 3)
  mat &lt;- rbind(time, money, ownership, randomstuff)
  
  dat &lt;- c(1, 0, 2, 0, 3, 0)  
  obj &lt;- matrix(dat,nrow=1) 
  </code></pre>
  
  <p>I am running them through a function:</p>
  
  <pre><code>f &lt;- function(mat,obj){fake function outputting a vector the same length as obj}
  
  soln &lt;- f(mat, obj).
  </code></pre>
  
  <p>where <code>soln</code> is a 1x6 matrix.</p>
  
  <p>How could I transform (elegantly - this is actually a 70000+ column matrix) the matrices <code>mat</code> and <code>obj</code> to:</p>
  
  <pre><code>time &lt;- c(1, 2, 3)
  money &lt;- c(2, 4, 6)
  ownership &lt;- c(1, 1, 1)
  mat &lt;- rbind(time, money, ownership, randomstuff) 
  
  dat &lt;- list(1, 2, 3)  
  obj &lt;- matrix(dat,nrow=1) 
  </code></pre>
  
  <p>with the <code>soln</code> being a 1x3 matrix.</p>
  
  <pre><code>soln=          [,1]     [,2]      [,3]     
         [1,] 4.151969 5.759826  5.537563 
  </code></pre>
  
  <p>where the decision to exclude a column from <code>mat</code> is based on the value in <code>ownership[]=0</code> and the same for <code>obj</code>.  The added difficulty, is that I need to be able to assign the output in <code>soln</code> to the mapped to the corresponding original position in a larger <code>SOLN</code> matrix.  In this case columns 1,3,5.  Ownership is randomly assigned, so there will be no pattern other than the zeros described above.</p>
  
  <p>The suggestion to use:</p>
  
  <pre><code>obj2 &lt;- obj[, as.logical(ownership), drop = FALSE]
  mat2 &lt;- mat[, as.logical(ownership)]
  </code></pre>
  
  <p>works perfectly for that piece.  How do I put the <code>soln</code> values in positions 1,3,5 of a larger <code>SOLN</code> matrix? The <code>SOLN</code> matrix below is an example of possible output.  In this case, I want columns 1, 3, and 5 to be filled by this function.  Subsequent operations (same operation different <code>ownership</code>) will fill columns 2, 4 and 6. </p>
  
  <pre><code>SOLN =          [,1]    [,2]     [,3]     [,4]     [,5]     [,6]
         [1,] 4.151969 1.08251 5.759826 3.368613 5.537563 3.471643
  </code></pre>
  
  <p>Any ideas?</p>