How to get AST as a list in R

浪子不回头ぞ 提交于 2021-01-28 00:26:57

问题


I have strings, which describe mathematical formulas and I would like to convert it into lists of meaningful parts. The function ast_ does know how to parse it, to displays it as an Abstract Syntax Tree but does not return the AST. I am looking for a function which does return the tree.

bb <- "(media.urin_A + media.urin_B)/2"
lazyeval::ast_(rlang::parse_expr(bb))
> lazyeval::ast_(rlang::parse_expr(bb))
┗ ()
 ┗ `/
 ┗ ()
  ┗ `(
  ┗ ()
   ┗ `+
   ┗ `media.urin_A
   ┗ `media.urin_B
 ┗  2 

回答1:


You can construct one recursively using as.list() and map_if from purrr:

getAST <- function(ee) purrr::map_if(as.list(ee), is.call, getAST)

# Example usage on expressions:
getAST( quote(log10(a+5)/b) )
# List of 3
#  $ : symbol /
#  $ :List of 2
#   ..$ : symbol log10
#   ..$ :List of 3
#   .. ..$ : symbol +
#   .. ..$ : symbol a
#   .. ..$ : num 5
#  $ : symbol b

# Example usage on strings:
getAST( str2lang("(media.urin_A + media.urin_B)/2") )
# List of 3
#  $ : symbol /
#  $ :List of 2
#   ..$ : symbol (
#   ..$ :List of 3
#   .. ..$ : symbol +
#   .. ..$ : symbol media.urin_A
#   .. ..$ : symbol media.urin_B
#  $ : num 2


来源:https://stackoverflow.com/questions/60083614/how-to-get-ast-as-a-list-in-r

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!