使用 & 和 grepl 子设置数据 table

Sub-setting data table using & and grepl

我有一个列名如下的数据集:

names(d)
 [1] "Code"        "LX(RI)"      "LX(VO)"      "LX(MV)"      "LX(WC189)" "LX(WC035)"
 [7] "NX(RI)"      "NX(VO)"      "NX(MV)"      "NX(WC189)"   "NX(WC035)" "AX(RI)"     
[13] "AX(VO)"      "AX(MV)"      "AX(WC189)"   "AX(WC035)"   "SX3I(RI)"  "SXI(VO)"    
[19] "SXI(MV)"     "TX(RI)"      "TX(VO)"      "TX(MV)"      "TX(WC189)" "TX(WC035)"

每一列都有几千行与之关联。我想要做的是使用 grepl 根据以 RI 结尾并保留代码列的数据 table 的列进行子集化。

目前我已经弄清楚如何将所有 RI 列子集化为一个新的 data.table,但我不知道如何包含代码列。

我目前有:

RI <- d[, grepl("\(RI", names(d)), with = FALSE]

这给了我想要的:

names(RI)
[1] "LX(RI)" "NX(RI)" "AX(RI)" "SX3I(RI)" "TX(RI)"

我一直在尝试(注意我已经包含了 &Code):

RI <- d[, grepl("\(RI&Code", names(d)), with = FALSE]

我想要return一个数据table具有以下列:

[1] "LX(RI)" "NX(RI)" "AX(RI)" "SX3I(RI)" "TX(RI)" "Code"

以上是我想要的输出。但是代码什么都不做,returns 是一个空数据 table.

几个问题:

试试这个

ab <- c("Code","LX(RI)","LX(VO)","LX(MV)","TX(RI)","NX(RI)","NX(RI)")


ab[grepl("Code|RI",ab)]

[1] "Code"   "LX(RI)" "TX(RI)" "NX(RI)" "NX(RI)"