regex - 使用 dplyr 从 data.table 中删除列

标签 regex r data.table dplyr

我正在尝试使用 dplyr 包中的 select 函数删除 data.table 中的列,但遇到了当没有列匹配我的搜索模式时出错。

使用标准的 iris 数据集并导入适当的包,

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

有什么方法可以删除与给定正则表达式匹配的任何列(如果它们存在),否则保持表不变?

最佳答案

试试这个

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

关于regex - 使用 dplyr 从 data.table 中删除列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29927253/

相关文章:

java - 正则表达式 foo_bar_number 为 2 个字符串 [foo_bar, number]?

javascript - RegEx 在测试器中工作,而不是在现场使用 JavaScript

r - 增加 R iGraph 顶点之间的空间

r - 为什么列选择的 data.table 表示法会影响速度

r - 使用data.table按组抽样而不重复

带量词的 Java 正则表达式 : replace matches by dynamically generated string

regex - 将部分匹配模式保存到变量

php - 扩展 PHP 以与 R 编程语言通信

r - r中使用prewhiten函数出错

r - 贬低 R data.table : list of columns