title: looping over a subset of variables in R by name
body: <p>Data frame <code>have</code> contains a few thousand variables. One variable is a treatment indicator called <code>treatgrp</code> which contains values of 1, 2, or 3). Five other variables are called: <code>g_cA</code>, <code>r_cA</code>, <code>g_ccA</code>, <code>r_ccA</code>, and <code>g_grp</code>. They do not appear in order.</p>
  <p>I want to generate frequency tables comparing <code>treatgrp</code> to the five other variables of interest. I currently do so with some wallpaper syntax:</p>
  <pre><code>table(have$treatgrp, have$g_cA,   deparse.level = 2)
  table(have$treatgrp, have$r_cA,   deparse.level = 2)
  table(have$treatgrp, have$g_ccA,  deparse.level = 2)
  table(have$treatgrp, have$r_ccA,  deparse.level = 2)
  table(have$treatgrp, have$g_grp,  deparse.level = 2)
  </code></pre>
  <p>This does the job. But I'd like to call <code>table()</code> once and iterate over the five different variables of interest. I tried doing so this way:</p>
  <pre><code>myvars &lt;- c(&quot;g_cA&quot;, &quot;r_cA&quot;, &quot;g_ccA&quot;, &quot;r_ccA&quot;, &quot;g_grp&quot;)
  
  for (i in 1:length(myvars)){
    table(have$treatgrp, have[,myvars[i]],  deparse.level = 2)
  }
  </code></pre>
  <p>This doesn't result in an error message, but it also returns no output table.</p>
  <p>It may be obvious that I'm used to macros and arrays in SAS based on this question. But I'd like to learn at least one way to solve this problem. I have to do things that resemble this all the time, and figuring out a more elegant solution would save me a lot of time.</p>