R-使用非标准评估来检查字符串是否为有效的数学表达式

问题描述 投票:0回答:1

我想检查下面的字符串是否是有效的数学表达式:

s1 = 'sin(x)'
s2 = 'sin(x*m)'
s3 = 'sin'
s4 = 'sin(xm)'

通过'有效',我的意思是表达式是]的组合>

  1. 运算符(必须与变量或常量结合使用)
  2. 变量x和/或m
  3. 常量。
  4. 根据此定义,s1s2有效,而s3s4无效。

[为了识别字符串是否有效,我编写了一个函数checkFxn,该函数首先尝试将字符串转换为调用或其一部分。如果成功,则它将遍历调用树并检查上述条件。如果满足条件,则按原样返回呼叫。如果不是,则会引发错误。

checkFxn <- function(x) {

  lang <- str2lang(x)

  checkFxn2 <- function(y) {

    if(is.name(y)) {

      stopifnot(deparse(y) %in% c('x', 'm'))

    } else if(is.call(y)) {

      stopifnot(is.function(eval(y[[1]])) | is.primitive(eval(y[[1]])))

      lapply(y[-1], checkFxn2)

    } else {

      stopifnot(is.logical(y) | is.numeric(y) | is.complex(y))

    }

    return(y)

  }

  checkFxn2(lang)

}


#Applying checkFxn to s1-4
lapply(list(s1,s2,s3,s4), function(x) {try(checkFxn(x), silent = T)})
[[1]]
sin(x)

[[2]]
sin(x * m)

[[3]]
[1] "Error in checkFxn2(lang) : deparse(y) %in% c(\"x\", \"m\") is not TRUE\n"
attr(,"class")
[1] "try-error"
attr(,"condition")
<simpleError in checkFxn2(lang): deparse(y) %in% c("x", "m") is not TRUE>

[[4]]
[1] "Error in FUN(X[[i]], ...) : deparse(y) %in% c(\"x\", \"m\") is not TRUE\n"
attr(,"class")
[1] "try-error"
attr(,"condition")
<simpleError in FUN(X[[i]], ...): deparse(y) %in% c("x", "m") is not TRUE>

它似乎按预期工作,但我对使用eval感到谨慎,并想知道是否有人可以建议使用它吗?我知道它遵循通常的词法作用域规则,因此我担心它会在全局环境中评估变量-是否有办法限制其范围?我已经阅读了non-standard evaluation上的章节,但无法弄清楚。

而且,有没有一种方法可以识别基本函数或基元是否是数学运算符?我想使用比is.functionis.primitive更具体的内容。

我想检查以下字符串是否为有效的数学表达式:s1 ='sin(x)'s2 ='sin(x * m)'s3 ='sin's4 ='sin(xm)'由'valid ',我的意思是表达式是...

r eval lexical-scope non-standard-evaluation
1个回答
0
投票

[步骤1:

© www.soinside.com 2019 - 2024. All rights reserved.