如何识别 R 中不以特定模式开头的行

How to identify rows that are not starting with a certain pattern in R

我有一个数据 table,其中一列包含不同的字符,我想检查是否所有行都以“99”、“15”、“16"or "17”和有 4-5 个字符。

知道怎么做吗?我考虑过使用 grep,但它并没有真正起作用..!

谢谢

爱达

假设您的数据框名为 dat 并且 x 是感兴趣的列,以下将 return 所有以所需字符开头且具有 4 或5个字符:

dat[grepl("^(15|16|17|99)", dat$x) & nchar(dat$x) %in% 4:5, ]

至return行不符合条件:

dat[!(grepl("^(15|16|17|99)", dat$x) & nchar(dat$x) %in% 4:5), ]

以下是对您的评论的答复:

1) 检查所有行是否满足条件:

all(grepl("^(15|16|17|99)", dat$x) & nchar(dat$x) %in% 4:5)

2) 识别不符合条件的行:

which(!(grepl("^(15|16|17|99)", dat$x) & nchar(dat$x) %in% 4:5))