title: R: set variables type and levels in a data frame , based on list
body: <p>I have a data frame like this:</p>
  <pre><code>df &lt;- data.frame(
    v1 = sample(c(&quot;L1&quot;,&quot;L2&quot;),5,replace = TRUE), 
    v2 = sample(c(&quot;F1&quot;,&quot;F3&quot;),5,replace = TRUE),
    v3 = sample(seq(1,5),5,replace = T)
  )
  </code></pre>
  <p>I want (1) to set the type of the variables, based on a named list:</p>
  <pre><code>typs &lt;- list(&quot;v1&quot; = &quot;factor&quot;, &quot;v2&quot; = &quot;factor&quot;, &quot;v3&quot; = &quot;numeric&quot;)
  </code></pre>
  <p>and (2) to set the levels of the factor variables:</p>
  <pre><code>list.levels &lt;-  list(&quot;v1&quot; = c(&quot;L1&quot;,&quot;L2&quot;,&quot;L3&quot;), &quot;v2&quot; = c(&quot;F1&quot;,&quot;F2&quot;,&quot;F3&quot;))
  </code></pre>
  <p>Ideally, I would like to use a generalized approach, that could be applied to data frames with a dynamic number of columns.</p>