title: How to call dynamic variable name inside a function?
body: <p>I need to convert categorical variables into multiple dichotomous ("dummy") variables to use in a logistic regression. Say my data frame is: </p>
  
  <pre><code>    tdf &lt;- data.frame(first=sample(c("A", "B", "C", "D"), 100, replace=T),
                        lobe = sample(c("RUL", "RML", "RLL", "LUL", "LLL"), 100, replace=T),
                        continuous=sample(1:100, 100),
                        smoker = sample(c("never", "less20", "more20"), 100, replace=T)
                        )
  </code></pre>
  
  <p>I could manually do</p>
  
  <pre><code>first. &lt;- with (tdf,  factor (first))
  dummies &lt;-  model.matrix(~ first.)
  dummies &lt;- dummies[,-1]
  tdf &lt;- cbind(tdf, dummies)
  </code></pre>
  
  <p>Note that it is important to call the factor "first." (or more generally, "variable.") because the dummy variables will inherit this prefix into their respective names, making it easier to identify them later ('variable1.factor2', 'variable1.factor3' etc). </p>
  
  <p>My question is: How can do this using a function that would programatically assign variable names:</p>
  
  <pre><code>dummify &lt;- function(df, vectorOfColIndices) {
    cn &lt;- colnames(df) 
    for (i in vectorOfColIndices) {
      t. &lt;- with (tdf,  factor (df[i])) # temporary factor
      assign (cn[i], t.) # give it the proper 'Variable.' name
      dummies &lt;-  model.matrix(~ ????) # Stuck here: how do I call this newly created structure?
      ...
    }
  }
  </code></pre>
  
  <p>So that I can later transform a data frame like this:</p>
  
  <pre><code>vd &lt;- c(1,2,4) # columns that need to be converted into dummy vars
  df &lt;- dummify(df, vd)
  </code></pre>