这是 data.table 的已知行为,设定 with 选项
iris[iris$Species == 'setosa' & iris$Sepal.Length > 5.5, grepl('Sepal', colnames(iris)), with=FALSE]
# 简化
iris[Species == "setosa" & Sepal.Length > 5.5, grepl("Sepal", colnames(iris)), with = FALSE]
# 再简化
iris[Species == 'setosa' & Sepal.Length > 5.5, .SD, .SDcols = patterns('Sepal')]
或者用 mget 将字符串向量转为变量
iris[iris$Species == 'setosa' & iris$Sepal.Length > 5.5, mget(grep("Sepal", colnames(iris), value = TRUE))]