title: Save results from a function that contains a for loop
body: <p>expeRts</p>
  
  <p>I created a function that counts the number of rows that meet some conditions. I made this function because one of the conditions has to take different labels that I have in a vector - I did not use filter since I would have to change one of the conditions on the filter and go back to the original data frame over and over.
  My function:</p>
  
  <pre><code>counting &lt;- function(df, na.rm = TRUE, ...) {
  
      for (i in seq_along(counties)) {   
        observations&lt;-
        nrow(subset(financial_environment, 
  financial_environment$county==counties[i]
                    &amp; population&gt; 500000))
        print(observations) }
  }
  counting(financial_environment)
  </code></pre>
  
  <p>The problem is how can I save the outputs of the console in a vector (that has a for loop inside). <strong>I would like to have this vector to create a data frame with previous vectors in my code.</strong> </p>
  
  <p>I read on other stackoverflow questions but the functions look a bit basic compared with the one I made. Those answers recommend the following:</p>
  
  <p>Create a vector where the results would be saved.
  <code>results &lt;- vector("numeric", 650L)</code></p>
  
  <p>Then just change a line of the function:</p>
  
  <pre><code>counting &lt;- function(df, na.rm = TRUE, ...) {
  
      for (i in seq_along(counties)) {   
        observations&lt;- 
        nrow(subset(financial_environment, 
  financial_environment$county==counties[i]
                    &amp; population&gt; 500000))
        print(observations)}
  </code></pre>
  
  <p>Next, I would just apply the function to the data frame and see the "results" vector
  <code>
  counting(financial_environment)
  results
  </code>
  By doing this, the "results" vector has only zero's inside.</p>
  
  <p>I tried also with <code>sapply</code>, but the console showed 1000 obsevartions. I noticed that the results were repeated i.e. the last 450 outpts were the first 450 outputs when applied the function.</p>
  
  <p>I would reaaly appreciate your comments and suggestions.</p>