问题描述
给出一个rlang表达式:
expr1 <- rlang::expr({
d <- a + b
})
如何检索表达式中引用的对象的名称?
> extractObjects(expr1)
[1] "d" "a" "b"
更好的方法是如何检索对象名称并按“必需”(输入)和“创建”(输出)对它们进行分类?
> extractObjects(expr1)
$created
[1] "d"
$required
[1] "a" "b"
解决方法
基本功能all.vars
做到了:
〉all.vars(expr1)
[1] "d" "a" "b"
或者,您可以使用all.names
来获取表达式中的所有名称,而不仅仅是不用作调用或运算符的名称:
〉all.names(expr1)
[1] "{" "<-" "d" "+" "a" "b"
别误导:这个结果是正确的! 所有这些不仅出现在a
,b
和d
。
但这可能不是您想要的。
事实上,我假设您想要的对应于抽象语法树(AST)中的叶子标记-换句话说,除了函数调用(以及运算符,它们也是函数调用)之外的所有内容。
表达式的语法树如下所示: 1
{
|
<-
/\
d +
/ \
a b
获取此信息意味着要进行AST:
leaf_nodes = function (expr) {
if(is.call(expr)) {
unlist(lapply(as.list(expr)[-1L],leaf_nodes))
} else {
as.character(expr)
}
}
〉leaf_nodes(expr1)
[1] "d" "a" "b"
借助AST表示,我们还可以找到输入和输出:
is_assignment = function (expr) {
is.call(expr) && as.character(expr[[1L]]) %in% c('=','<-','<<-','assign')
}
vars_in_assign = function (expr) {
if (is.call(expr) && identical(expr[[1L]],quote(`{`))) {
vars_in_assign(expr[[2L]])
} else if (is_assignment(expr)) {
list(created = all.vars(expr[[2L]]),required = all.vars(expr[[3L]]))
} else {
stop('Expression is not an assignment')
}
}
〉vars_in_assign(expr1)
$created
[1] "d"
$required
[1] "a" "b"
请注意,此函数不能很好地处理复杂的分配(例如d[x] <- a + b
或f(d) <- a + b
之类的东西。
1 lobstr::ast
以不同的方式显示语法树,即为
█─`{`
└─█─`<-`
├─d
└─█─`+`
├─a
└─b
…,但是上面的表示在R之外更常规,我发现它更直观。
,另一种解决方法是extract the abstract symbolic tree explicitly:
getAST <- function(ee) purrr::map_if(as.list(ee),is.call,getAST)
str(getAST(expr1))
# List of 2
# $ : symbol {
# $ :List of 3
# ..$ : symbol <-
# ..$ : symbol d
# ..$ :List of 3
# .. ..$ : symbol +
# .. ..$ : symbol a
# .. ..$ : symbol b
然后遍历AST以查找分配:
extractObjects <- function(ast)
{
## Ensure that there is at least one node
if( length(ast) == 0 ) stop("Provide an AST")
## If we are working with the assigment
if( identical(ast[[1]],as.name("<-")) ) {
## Separate the LHS and RHS
list(created = as.character(ast[[2]]),required = sapply(unlist(ast[[3]]),as.character))
} else {
## Otherwise recurse to find all assignments
rc <- purrr::map(ast[-1],extractObjects)
## If there was only one assignment,simplify reporting
if( length(rc) == 1 ) purrr::flatten(rc)
else rc
}
}
extractObjects( getAST(expr1) )
# $created
# [1] "d"
#
# $required
# [1] "+" "a" "b"
然后您可以根据需要filter math operators out。
,这很有趣。我认为从概念上讲,在所有可能的表达式中可能不清楚输入和输出的确切含义。如果您查看可以用lobstr::ast()
进行可视化的所谓抽象语法树(AST),则它看起来像这样。
因此,在简单的情况下,当您始终拥有LHS <- operations on RHS variables
时,如果您迭代AST,则总是在<-
运算符之后立即获得LST。如果您分配z <- rlang::expr(d <- a+b)
,则z
的行为类似于列表,例如,您可以执行以下操作:
z <- rlang::expr(d <- a+b)
for (i in 1:length(z)) {
if (is.symbol(z[[i]])) {
print(paste("Element",i,"of z:",z[[i]],"is of type",typeof(z[[i]])))
if (grepl("[[:alnum:]]",z[[i]])) {print(paste("Seems like","is a variable"))}
} else {
for (j in 1:length(z[[i]])){
print(paste("Element",j,paste0("of z[[","]]:"),z[[i]][[j]],typeof(z[[i]][[j]])))
if (grepl("[[:alnum:]]",z[[i]][[j]])) {print(paste("Seems like","is a variable"))}
}
}
}
#> [1] "Element 1 of z: <- is of type symbol"
#> [1] "Element 2 of z: d is of type symbol"
#> [1] "Seems like d is a variable"
#> [1] "Element 1 of z[[3]]: + is of type symbol"
#> [1] "Element 2 of z[[3]]: a is of type symbol"
#> [1] "Seems like a is a variable"
#> [1] "Element 3 of z[[3]]: b is of type symbol"
#> [1] "Seems like b is a variable"
由reprex程序包(v0.3.0)于2020-09-03创建
如您所见,这些树很快就会变得复杂和嵌套。因此,在像您的示例这样的简单情况下,假设变量使用字母数字表示形式,我们可以识别“对象”(如您所说的)是什么以及什么是运算符(与{{1}不匹配) }正则表达式)。如您所见,由于类型始终为[[:alnum:]]
(下面的symbol
和z
一样,language
不能用来区分对象和运算符,所以我们可以确定z[[3]]
是否为z[[i]]
,如果不是,请更深入地研究。)然后,您可能(冒着险)尝试将symbol
之后立即出现的对象归类为“输出”,其余的归类为“输入”,但是我对此没有太大的信心,尤其是对于更多复杂的表达式。
简而言之,这都是推测性的。