title: R: How to write a function that gets the levels of column in a data.table
body: <p>Some data:</p>
  
  <pre><code>require(data.table)
  set.seed(123)
  DT &lt;- data.table(factor = c("a", "b", "c"), num = rpois(6, 30))
  DT[["factor"]] &lt;- factor(DT[["factor"]])
  levels(DT[["factor"]])
  # [1] "a" "b" "c"
  </code></pre>
  
  <p>I'm trying to write a function that gets the levels of the the DT. Here's what I've attempted so far:</p>
  
  <pre><code>get_levels &lt;- function(data, factor){
    data = substitute(data)
    factor = substitute(factor)
    factor_levels = levels(data[["factor"]])
    print(factor_levels)
  }
  
  get_levels(DT, factor)
  
  get_levels2 &lt;- function(data, factor){
    data = substitute(data)
    factor = substitute(factor)
    factor_levels = levels(data[[factor]])
    print(factor_levels)
  }
  
  get_levels2(DT, factor)
  
  
  get_levels3 &lt;- function(data, factor){
    data = substitute(data)
    factor = substitute(factor)
    factor_levels = levels(eval(data[[deparse(factor)]]))
    print(factor_levels)
  }
  
  get_levels3(DT, factor)
  </code></pre>
  
  <p>I'm getting this error:</p>
  
  <pre><code>Error in data[["factor"]] : object of type 'symbol' is not subsettable
  </code></pre>
  
  <p>and this one:</p>
  
  <pre><code>Error in data[[deparse(factor)]] : 
    object of type 'symbol' is not subsettable
  </code></pre>
  
  <p>As i don't have much experience programming i don't know exactly what's the purpose for the functions used for passing variables in functions: <code>substitute</code>, <code>deparse</code>, <code>eval</code>, <code>parse</code>. I've been reading the documentation and i'm not finding it very clear. So it would be interesting if someone could provide a clearer use for each function or perhaps point to resources to learn more about it. </p>