title: R: Loop to filter dataframe and print mean of column of filtered data into new dataframe
body: <p>I have this dataframe called <code>PlantGroNoT.RCP2.first.0</code> (randomly sampled it with dput()). </p>
  
  <pre><code>structure(list(Year = c(2040L, 2068L, 2096L, 2049L, 2072L, 2042L, 
  2087L, 2047L, 2076L, 2075L, 2052L, 2054L, 2034L, 2060L, 2041L, 
  2031L, 2067L, 2080L, 2055L, 2067L, 2095L, 2097L, 2097L, 2077L, 
  2057L, 2038L, 2052L, 2095L, 2043L, 2075L), DOY = c(78L, 13L, 
  20L, 364L, 23L, 14L, 352L, 72L, 54L, 2L, 1L, 5L, 53L, 43L, 63L, 
  26L, 21L, 30L, 360L, 22L, 46L, 62L, 355L, 4L, 61L, 355L, 75L, 
  51L, 46L, 39L), DAP = c(93L, 28L, 35L, 14L, 38L, 29L, 2L, 87L, 
  69L, 17L, 16L, 20L, 68L, 58L, 79L, 41L, 36L, 45L, 10L, 37L, 61L, 
  78L, 5L, 20L, 77L, 5L, 90L, 66L, 61L, 54L), NSTD = c(0.244, 0, 
  0.023, 0, 0, 0, 0, 0.547, 0, 0, 0, 0, 0, 0, 0.148, 0, 0, 0.001, 
  0, 0, 0.186, 0.443, 0, 0, 0.278, 0, 0.403, 0.16, 0.085, 0.069
  ), RCP = c("2", "4", "4", "4", "2", "4", "8", "4", "8", "4", 
  "4", "4", "8", "4", "4", "2", "8", "8", "8", "4", "8", "2", "4", 
  "8", "4", "8", "4", "4", "8", "2")), row.names = c(5634575L, 
  1218676L, 788139L, 7051284L, 6262001L, 1122307L, 3560772L, 3925983L, 
  2584130L, 3401700L, 1217186L, 1455727L, 2993448L, 597952L, 5893799L, 
  6696664L, 2345802L, 3105731L, 6347255L, 5005396L, 3330449L, 780805L, 
  2522272L, 3668256L, 2099405L, 818891L, 1123257L, 5237622L, 1259779L, 
  1623133L), class = "data.frame")
  </code></pre>
  
  <p>I want to filter it by <code>RCP</code>, <code>DAP</code>and <code>Year</code>. From the result of this filter, I would like to take the mean of<code>NSTD</code>and print it into the <code>NSTDmean</code> column of the dataframe <code>HO1_2020_RCP2_stress</code></p>
  
  <p><code>DAP</code> ranges from 0 to 114, so in the first cell of <code>HO1_2020_RCP2_stress$WSPDmean</code> I would like to have the NSTDmean for <code>DAP</code>==0, in the second cell the mean for <code>DAP</code>==1, etc. </p>
  
  <p>I created this loop to do the job. </p>
  
  <pre><code>i = -1
    repeat{
      i= i+1
      PlantGroNoT.RCP2.first.0 &lt;- filter(PlantGroNoT_1, RCP==2 &amp; DAP==i &amp; Year&lt;=2060)
      H01_2020_RCP2_stress$NSTDmean &lt;- mean(PlantGroNoT.RCP2.first.0$NSTD, na.rm=TRUE)
      if (i&gt;114)
        break
    }
  
  </code></pre>
  
  <p>The filter and mean calculation itself work.</p>
  
  <p>However, the loop does not return the <code>NSTDmean</code> correctly in the <code>HO1_2020_RCP2_stress$WSPDmean</code> column. It always prints the value for the last i (i.e. here DAS==114) for the whole <code>NSTDmean</code> column. </p>