在R中检查给定的字符串是否为数学函数

R B*_*Bud -4 regex math r

我有这样的表达方式abs(iodlin_vod2*1e6)/(array*nfin*nrx*nfinger*weff).我的代码使用分割此表达式strsplit.现在,根据这个结果,我应该检查每个单词是否是数学函数,如果不是,我应该执行一些操作.如果它是数学函数,我会坚持检查这个词.有人可以请帮助.

Qsn编辑:这是结果 strsplit

sstemp
[1] "abs"          "iodlin_vod2 " " 1e+06"       "array "       " nfin "       
" nrx "       
[7] " nfinger "    " weff" 
Run Code Online (Sandbox Code Playgroud)

我想消除abs1e+06从进一步的操作在我的代码.

Rol*_*and 5

首先让我们看一下调用树:

ttt <- "abs(str1*1e6)/(str2*str3)"
library(pryr)
call_tree(parse(text=ttt))
#\- ()
#  \- `/
#  \- ()
#    \- `abs
#    \- ()
#      \- `*
#      \- `str1
#      \-  1e+06
#  \- ()
#    \- `(
#    \- ()
#      \- `*
#      \- `str2
#      \- `str3
Run Code Online (Sandbox Code Playgroud)

另见哈德利的书.

现在让我们以机器可用的格式创建它并清理一下:

test <- gsub("\\\\\\-|\\s*|`", "",
          unlist(
            strsplit(
              vapply(parse(text = ttt), pryr:::tree, 
                     character(1), width = getOption("width")), 
            "\\n")
          )
        )
#[1] "()"    "/"     "()"    "abs"   "()"    "*"     "str1"  "1e+06" "()"    "("     "()"    "*"     "str2"  "str3"
Run Code Online (Sandbox Code Playgroud)

然后我们可以测试:

vapply(test, function(x) is.function(tryCatch(getFunction(x), error = function(cond) NA)), logical(1))
#   ()     /    ()   abs    ()     *  str1 1e+06    ()     (    ()     *  str2  str3 
#FALSE  TRUE FALSE  TRUE FALSE  TRUE FALSE FALSE FALSE  TRUE FALSE  TRUE FALSE FALSE 
Run Code Online (Sandbox Code Playgroud)

正如你看到的,有四种不同的功能:/,abs,*,和(在此表达.

如果表达式中有一个带有函数名的非函数对象,则此解决方案将失败.