R-Grep在结果中包含NA值

时间:2019-04-27 18:26:08

标签: r

我正在尝试使用grep过滤我的数据,但还要在结果中包括NA,由于它们与grep表达式不匹配,因此目前已将其删除。

platform        x86_64-w64-mingw32
version.string  R version 3.5.3 (2019-03-11)

样本数据

   value expected_result actual_result
1  10001            Pass          Pass             
2      0            Pass          Pass
3      6            Pass          Pass
4  20004            Pass          Pass
5     NA            Pass          Fail
6   4829            Fail          Fail
7    521            Fail          Fail
8     89            Fail          Fail
9  40012            Fail          Fail
10 47321            Fail          Fail

代码

df <- df[grep("(\\b\\d{1}\\b)|([0-9]{1}[0]{3}[0-9]{1})", df$value),]

逻辑规则

1)该值将包含0到5个数字字符。

2)应该保留的三个值是:

a)一位数据。 (示例值2和3)

b)没有数据或不适用(示例值5)

c)数据的五位数,但中间的三位数必须全部为零。 (示例值1和4)

1 个答案:

答案 0 :(得分:3)

要包括NA行,请在is.na上用|创建第二个条件,并与grepl(OR)联接起来

df[grepl("(\\b\\d{1}\\b)|([0-9]{1}[0]{3}[0-9]{1})", df$value)|is.na(df$value),]
#   value expected_result actual_result
#1 10001            Pass          Pass
#2     0            Pass          Pass
#3     6            Pass          Pass
#4 20004            Pass          Pass
#5    NA            Pass          Fail

或者使其更紧凑

grepl("^\\d$|^([1-9]0{3}[1-9]$)", df$value)|is.na(df$value)

数据

df <- structure(list(value = c(10001L, 0L, 6L, 20004L, NA, 4829L, 521L, 
89L, 40012L, 47321L), expected_result = c("Pass", "Pass", "Pass", 
"Pass", "Pass", "Fail", "Fail", "Fail", "Fail", "Fail"), actual_result = c("Pass", 
"Pass", "Pass", "Pass", "Fail", "Fail", "Fail", "Fail", "Fail", 
"Fail")), class = "data.frame", row.names = c("1", "2", "3", 
"4", "5", "6", "7", "8", "9", "10"))