Create New Columns Within a Loop
<p>I am wanting to create variables age10, age20, age30, etc. for a specified data set. The input for the function add_ages is a data frame named df, where the new variables are created based on their relation to the existing variable age.</p>

<pre><code>df &lt;- data.frame(age=sample(1:100,10,replace=T))

add_ages &lt;- function(d){
  for(i in seq(10,100,10)){
    d[,paste0("age",i)] &lt;&lt;- ifelse(i&gt;=d[,"age"] &amp; d[,"age"]&lt;i+10,1,0)
  }
}

add_ages(d=df)
</code></pre>

<p>However, when I run the code above, I get the following error:</p>

<pre><code>Error in d[, paste0("age", i)] &lt;&lt;- ifelse(i &gt;= d[, "age"] &amp; d[, "age"] &lt;  : 
  object 'd' not found
</code></pre>

<p>I'm not sure I understand why d cannot be found, when I am defining it to be df.  Any thoughts?</p>