Subset data frame based on character vector of column names
<p>Rookie question - thanks in advance for patience...</p>

<p>I have a dataframe:</p>

<pre><code>vals &lt;- c(1,1,1,1)
testdf &lt;- data.frame("var1"=vals, "var2"=vals, "var3"=vals)
</code></pre>

<p>I have a character vector of variable names:</p>

<pre><code>varnames &lt;- c("var1", "var2")
</code></pre>

<p>This is a character vector b/c I use it to generate a formula earlier in the script.</p>

<p>I'd like to subset a dataframe such that variables in varnames are excluded, e.g.</p>

<pre><code>newDF &lt;- subset(df, select=-varnames)
</code></pre>

<p>This creates an error since <code>subset</code> expects names instead of characters. So, I use <code>lapply</code> to change the characters to names:</p>

<pre><code>varnames &lt;- lapply(varnames, as.name)
</code></pre>

<p>The result of this lapply function is a named(?) and nested(?) list.</p>

<pre><code>[[1]]
var1

[[2]]
var2

[[3]]
var3
</code></pre>

<p>Here's where I get lost (I feel like Mugatu on crazy pills... is this confusing to anyone else!?). I can see that each value has correctly been changed from character to name, but it's in this weird nested structure - so when I try to subset, I get an error.</p>

<p>I've tried various solutions to unnest and unname, but with no success. This must be something easy I'm missing.</p>

<p>As a bonus - can someone tell me why it is ever useful for lapply to return this nested named list instead of simple vector? It seems very different than, for instance, Python. Thank you.</p>