Removing columns from data.table using dplyr

I am trying to delete columns in data.table

using a function select

in a package dplyr

and I am running into an error when the columns do not match the search pattern.

Using a standard dataset iris

and importing the appropriate packages,

library(dplyr)
library(data.table)
select(data.table(iris), -matches("^Petal"))
# returns a table with three columns: Sepal.Length, Sepal.Width, Species
select(data.table(iris), -matches("^ER[[:digit:]]+$"))
# displays error message:
# Error in data.table::setnames(out, names(vars)) : x has no column names

      

Is there a way to remove any columns that match a given regex (if they exist) and leave the table unmodified otherwise?

+3


source to share


1 answer


try it



 iris[, !grepl("^ER[[:digit:]]+$", names(iris))]

      

+4


source







All Articles