title: R - multiple loop counter variables
body: <p>I need to write loops where each iteration has a unique set of variable values. It is not a nested loop "for each i do (for each j do)" type problem. Below is just an example problem, what the loop is doing is not important, it is being able to use multiple variables for each iteration for the loop.</p>
  
  <p>simple loop:</p>
  
  <pre><code>df &lt;- data.frame(num = 1:5)
  lookup &lt;- data.frame(colors = c("red", "green", "blue"), 
                       pets = c("cat", "dog", "rabbit"),
                       stringsAsFactors = FALSE)
  for (color in lookup$colors) {
    df[, color] &lt;- 1
  }
  </code></pre>
  
  <p>what I want to do (pseudo code):</p>
  
  <pre><code>for (color, pet in lookup$colors, lookup$pets) {
    df[, color] &lt;- pet
  }
  </code></pre>
  
  <p>The best approach I have come up with is below, but the additional r[" "] makes the code harder to read:</p>
  
  <pre><code>for (i in 1:nrow(lookup)) {
    r &lt;- unlist(lookup[i, ])
    df[, r["colors"]] &lt;- r["pets"]
  }
  
  df
    num red green   blue
  1   1 cat   dog rabbit
  2   2 cat   dog rabbit
  3   3 cat   dog rabbit
  4   4 cat   dog rabbit
  5   5 cat   dog rabbit
  </code></pre>
  
  <p>I would like to know what the best generalisable approach to this kind of problem is. In many cases, you could replace the loop with a function to be called for each set of variables, but functions aren't suitable in certain cases.</p>