title: Loop to create dummy variable R
body: <p>I am trying to generate dummy variables (must be 1/0) using a loop based on the most frequent response of a variable. After lots of googling, I haven't managed to come up with a solution. I have extracted the most frequent responses (strings, say the top 5 are "A","B",...,"E") using </p>
  
  <p><code>top5&lt;-names(head(sort(table(data$var1), decreasing = TRUE),5)</code></p>
  
  <p>I would like the loop to check if another variable ("var2") equals A, if so set =1, OW =0, then give a summary using aggregate(). In Stata, I can refer to the looped variable i using `i' but not in R...  The code that does not work is:</p>
  
  <pre><code>for(i in top5) {
     data$i.dummy &lt;- ifelse(data$var2=="i",1,0)
     aggregate(data$i.dummy~data$age+data$year,data,mean)
  }
  </code></pre>
  
  <p>Any suggestions?</p>