title: How can I do something like foreach in Stata using R?
body: <p>I'm new to R and am using Stata. I can loop through the variables using foreach and forvalue in Stata. </p>
  
  <p>I would like to loop over column rather than loop over row. For example, I have column named var1, var2, var3. And the data as below:</p>
  
  <pre><code>var1 var2 var3
    1    1   1   
    2   999  3
   999   2  999
  </code></pre>
  
  <p>I would like to recode all "999" values in the variables to missing. In Stata, I can do </p>
  
  <pre><code>forvalue i = 1(1)3{
    replace var`i' ="NA" if var`i' =="999"
  }
  </code></pre>
  
  <p>Therefore, I have the outcome like</p>
  
  <pre><code>var1 var2 var3
    1    1   1   
    2   NA   3
    NA   2  NA
  </code></pre>
  
  <p>Also, if I have column named ht, wgt, bmi, I would like to calculate the mean of the column and store the mean in new column with respective name. The dataset is as below:</p>
  
  <pre><code> ht     wgt   bmi
  154.5  43.1 18.1
  164.2  63   23.4
  </code></pre>
  
  <p>In Stata, I can do</p>
  
  <pre><code>foreach i of varlist ht wgt bmi{
    gen `i'mean = mean(`i')
  }
  </code></pre>
  
  <p>And the outcome will be</p>
  
  <pre><code> ht    wgt   bmi  htmean wgtmean bmimean
  154.5  43.1 18.1  159.35  53.05   20.75
  164.2  63   23.4  159.35  53.05   20.75
  </code></pre>
  
  <p>I've no idea how to do using R.</p>