我有一个像这样的data.table,但有更多列:
Pclass Age Sibsp Parch
0 3 22.0 1 0
1 1 38.0 1 0
2 3 26.0 0 0
我想只检索那些包含与字符串匹配的行的DetailCol1' ARP'。
This question在指向library(data.table)
the_dt = data.table(DetailCol1=c("Deets1","Deets2","Deets3","Deets4"), DetailCol2 = c("MoreDeets1","MoreDeets2","MoreDeets3","MoreDeets4"), DataCol1=c("ARP","AARPP","ABC","ABC"), DataCol2=c("ABC","ABC","ABC","ARPe"), DataCol3 = c("ABC", "ARP", "ABC","ABC"))
时非常有用,但我仍然不确定如何对多列进行此操作,特别是如果有几十列我想要搜索
例如,这就是我在DataCol1中搜索的方式
like
,但我如何在DataCols 1-100中进行相同的搜索?
答案 0 :(得分:3)
我们可以在.SDcol
中指定要比较的列,使用lapply
循环它,使用%like%
将其转换为逻辑,检查每行是否至少有一个TRUE Reduce
,用于对来自' DetailCol1'的元素进行子集化。
the_dt[the_dt[, Reduce(`|`, lapply(.SD, `%like%`, "ARP")),
.SDcols= DataCol1:DataCol3], DetailCol1]