title: How can I collapse multiple columns and to generate new variables from the different levels/values that were collapsed?
body: <p>I have a dataset (df) similar to this one: </p>
  
  <pre><code>df &lt;- data.frame("ID"=c(1, 1, 1, 2, 2), 
                   "Method of payment"=c("cash","liabilities", 
                                         "shares", "cash", NA), 
                   "USD"=c(110, 130, 200, 100, NA), 
                   "var3"=c(1500, NA, NA, "ab", "bc"))
  df
  #   ID Method.of.payment USD var3
  # 1  1              cash 110 1500
  # 2  1       liabilities 130 &lt;NA&gt;
  # 3  1            shares 200 &lt;NA&gt;
  # 4  2              cash 100   ab
  # 5  2              &lt;NA&gt;  NA   bc
  </code></pre>
  
  <p>And I would like to have: </p>
  
  <pre><code>data.frame("ID"=c(1, 2), 
             "Method of payment"=c("cash, liabilities, shares", "cash"), 
             "Cash"=c(110, 100), 
             "Liabilities"=c(130, 0),
             "Shares"=c(200, 0),
             "var3"=c(1500, "ab,bc"))
  
  #   ID         Method.of.payment Cash Liabilities Shares  var3
  # 1  1 cash, liabilities, shares  110         130    200  1500
  # 2  2                      cash  100           0      0 ab,bc
  </code></pre>
  
  <p>Therefore, I would like to </p>
  
  <ol>
  <li>collapse the variables "method of payment" and "var3" in order to have only one row per ID, having all the levels/values linked to an ID pasted in one row; </li>
  <li>generate new variables from existing levels of the factor variable method of payment ("cash", "liabilities", "shares") whose values should be the corresponding values of the variable USD or 0 if there is no corresponding value.</li>
  </ol>
  
  <p>I am working with a very large dataset, so I am looking for something that works also on large data. I hope it is clear.</p>