Removing all columns with a name on the fly
<p>I'm using <code>read_excel</code> for speed and simplicity to import an Excel file.</p>

<p>Unfortunately, there's as yet no capability of excluding selected columns which won't be needed from the data set; to save effort, I am naming such columns <code>"x"</code> with the <code>col_names</code> argument, which is easier than trying to keep track of <code>x1</code>, <code>x2</code>, and so on.</p>

<p>I'd then like to exclude such columns on the fly if possible to avoid an extra step of copying, so in pseudocode:</p>

<pre><code>read_excel("data.xlsx", col_names = c("x", "keep", "x"))[ , !"x"]
</code></pre>

<p>We can use the sample data set included with the <code>readxl</code> package for illustration:</p>

<pre><code>library(readxl)
DF &lt;- read_excel(system.file("extdata/datasets.xlsx", package = "readxl"),
                 col_names = c("x", "x", "length", "width", "x"), skip = 1L)
</code></pre>

<p>The approaches I've seen that work don't exactly work on the fly, e.g., having stored <code>DF</code>, we can now do:</p>

<pre><code>DF &lt;- DF[ , -grep("^x$", names(DF))]
</code></pre>

<p>This works but requires making a copy of <code>DF</code> by storing it, then overwriting it; I'd prefer to remove the columns in the same command as <code>read_excel</code> to allocate <code>DF</code> properly <em>ab initio</em>.</p>

<p>Other similar approaches require declaring temporary variables, which I prefer to avoid if possible, e.g.,</p>

<pre><code>col_names &lt;- c("x", "x", "length", "width", "x")
DF &lt;- read_excel(system.file("extdata/datasets.xlsx", package = "readxl"),
                 col_names = col_names, skip = 1L)[ , -grep("^x$", col_names)]
</code></pre>

<p>Is there a way to axe these columns without creating unnecessary temporary variables?</p>

<p>(I could convert to <code>data.table</code>, but am wondering if there's a way to do so without <code>data.table</code>)</p>