R:如何让 parse() 接受带有转义字符的正则表达式?

R: How to make parse() accept regular expressions with escaped characters?

我正在尝试使用 validator 包来检查我的数据 table 中的某些行是否包含正则表达式。

我用我要测试的列创建了一个向量(字段),然后将验证器规则的命令作为字符串粘贴在一起。

为了能够在 confront() 函数中使用规则,我使用 parse() 和 eval() 将字符串转换为表达式

以下示例按预期工作:

library(validate)

  data <- data.frame("Protocol_Number" = c("123", "A122"), "Numeric_Result" = c("-0.5", "1.44"))
  fields <- c("Protocol_Number", "Numeric_Result")
  
  # build validator commands for each field
  cmds <- paste("validator(",
                paste(
                  map_chr(
                    fields, function(x) paste0("grepl('^-?[0-9]', as.character(`", x, "`))")
                  ), collapse = ","),
                ")")
  
  # convert to rule and do the tests
  rule <- eval(parse(text = cmds))
  out <- confront(data, rule)
  summary(out)

但是,我想使用一个正则表达式来识别任何类型的数字而不是文本,就像在这个工作示例中一样

grepl('^-?[0-9]\d*(\.\d+)?$', c(1, -1, 0.5, "Not Done"))

当我尝试在上面的例子中使用这个正则表达式时,parse() 函数会抛出一个错误:

Error: '\d' is an unrecognized escape in character string starting "'^-?[0-9]\d"

这不起作用:

  
  # build validator commands for each field
  cmds <- paste("validator(",
                paste(
                  map_chr(
                    fields, function(x) paste0("grepl('^-?[0-9]\d*(\.\d+)?$', as.character(`", x, "`))")
                  ), collapse = ","),
                ")")
  
  # convert to rule and do the tests
  rule <- eval(parse(text = cmds))
  out <- confront(data, rule)
  summary(out)

如何让 parse() 接受转义字符?或者有更好的方法吗?

我们可以用 \

来逃避它
cmds <- paste("validator(",
                 paste(
                   map_chr(
                     fields, function(x) 
   paste0("grepl('^-?[0-9]\\d*(\\.\\d+)?$', as.character(`", x, "`))")
                   ), collapse = ","),
                 ")")

-测试

> rule <- eval(parse(text = cmds))
> 
>  out <- confront(data, rule)
> out
Object of class 'validation'
Call:
    confront(dat = data, x = rule)

Rules confronted: 2
   With fails   : 1
   With missings: 0
   Threw warning: 0
   Threw error  : 0