title: Replace Value in a Column Using a Loop and Custom Function - R
body: <p>I have a data.frame with a column (named "color") in which every value is "black." I also have created a function that can replace "black" with other colors depending on another column's value (the "growth" column value). I need to create a loop that uses this function to replace the values in the "color" column according to the "growth" value</p>
  
  <pre><code># Create a function
  check_it &lt;- function(x) 
    if(x&gt;500){
      return("green")
    } else if(x&lt;0) {
        return("red")
    } else {
      return("blue")
  }
  </code></pre>
  
  <pre><code># Create a loop using check_it
  for(x in 1:nrow(all_data)) {
       ...
  # Given this hint:
  # You can use 1:nrow(all_data) as a set of indices 
  # to do something like the following inside the loop:
  #    all_data[i, "color"] &lt;- 
  #    check_it( all_data[i, "growth"] )
  
  </code></pre>
  
  <p>Any suggestions?</p>
  
  <p>SAMPLE DATA</p>
  
  <pre><code>| station_id | timestamp | growth.x | growth.y | color |
  --------------------------------------------------------
  |     DB1    | 1/14/01   | 59.916   | 59.9164  | black |
  --------------------------------------------------------
  |     DB1    | 1/14/02   | 316.128  | 316.128  | black |
  --------------------------------------------------------
  |     DB1    | 1/14/03   | -12.456  | -12.456  | black |
  --------------------------------------------------------
  |     DB1    | 1/14/04   | 537.443  | 537.443  | black |
  --------------------------------------------------------
  </code></pre>
  
  <p>Thanks for the help! Thanks to the comments I was able to understand that my function wouldn't work without the proper arguments inserted (I just had "x") and didn't tell my function where to look for the "growth" value. </p>
  
  <p>Here's the code I ended up using:</p>
  
  <pre><code>check_it &lt;- function(x, ) 
    if(all_data[x, "growth.x"] &gt;500){
      return("green")
    } else if(all_data[x, "growth.x"] &lt;0) {
        return("red")
    } else {
      return("blue")
  }
  
  # Create a loop using check_it
  for(x in 1:nrow(all_data)) {
  
     all_data[x, "color"] &lt;- check_it(x, all_data)
  }
  </code></pre>