title: R: enumerate column combinations of a matrix
body: <p>(edit note: I changed the Title to "R: enumerate column combinations of a matrix", from "R grep: matching a matrix of strings to a list" to better reflect the solution)</p>
  
  <p>I am trying to match a matrix of strings to a list: so that i can ultimately use the matrix as a map in later operations on a <code>data.frame</code>. </p>
  
  <p>This first part works as intended, returning a list of all the possible pairs, triples and quad combinations (though perhaps this approach has created my bind?): </p>
  
  <pre><code>priceList &lt;- data.frame(aaa = rnorm(100, 100, 10), bbb = rnorm(100, 100, 10), 
              ccc = rnorm(100, 100, 10), ddd = rnorm(100, 100, 10), 
              eee = rnorm(100, 100, 10), fff = rnorm(100, 100, 10), 
              ggg = rnorm(100, 100, 10))
  
  getTrades &lt;- function(dd, Maxleg=3)
  {
      nodes &lt;- colnames(dd)
      tradeList &lt;- list()
      for (i in 2:Maxleg){
          tradeLeg &lt;- paste0('legs',i)
          tradeList[[tradeLeg]] &lt;- combn(nodes, i)
      }
      return(tradeList)
  }
  
  tradeCombos &lt;- getTrades(priceList, 4)
  </code></pre>
  
  <p>I'd now like to turn this list of possible combinations into trades. For example: </p>
  
  <pre><code>&gt; tradeCombos[[1]][,1]
  [1] "aaa" "bbb"
  </code></pre>
  
  <p>Needs to <em>eventually</em> become <code>priceList[,2] - priceList[,1]</code>, and so forth.  </p>
  
  <p>I have tried a few approaches with <code>grep</code> and similar commands, and feel that i've come close with the following: </p>
  
  <pre><code>LocList &lt;- sapply(tradeCombos[[1]], regexpr, colnames(priceList))
  </code></pre>
  
  <p>However the format is not quite suitable for the next step.  </p>
  
  <p>Ideally, <code>LocList[1]</code> would return something like: <code>1 2</code></p>
  
  <p>Assuming that the <code>tradeCombos[[1]][,1] == "aaa" "bbb"</code>. </p>
  
  <p>Can someone please help? </p>
  
  <p>__</p>
  
  <p>With help from all of the answers below, i've now got: </p>
  
  <pre><code>colDiff &lt;- function(x) 
  {
      Reduce('-', rev(x))
  }
  
  getTrades &lt;- function(dd, Maxleg=3)
  {
      tradeList &lt;- list()
      for (i in 2:Maxleg){
          tradeLeg &lt;- paste0('legs',i)
          tradeLegsList &lt;- combn(names(dd), i, 
              function(x) dd[x], simplify = FALSE)
          nameMtx &lt;- combn(names(dd), i)
          names(tradeLegsList) &lt;- apply(nameMtx, MARGIN=2, 
              FUN=function(x) paste(rev(x), collapse='*'))
          tradeList[[tradeLeg]] &lt;- lapply(tradeLegsList, colDiff) 
      }
      return(tradeList)
  }
  
  tradeCombos &lt;- getTrades(priceList, 4)
  </code></pre>
  
  <p>This retains the names of the constitutent parts, and is everything I was trying to achieve. </p>
  
  <p>Many thanks to all for the help. </p>