如何解析包含 `:=` 的表达式?

5

包含 := 的表达式无法很好地进行 deparse :

call1 <- quote(f(a = b(c = d)))
call2 <- quote(f(a := b(c := d)))

# nice
deparse(call1)
#> [1] "f(a = b(c = d))"

# not nice
deparse(call2)
# [1] "f(`:=`(a, b(`:=`(c, d))))"
我想要从call2获得以下输出:"f(a := b(c := d))"。 我正在寻找一种通用解决方案,可以像处理=<-一样,在所有情况下都能正确反解析:=
一个变通方法 这个变通方法利用了<<-具有类似或相同的优先级且不经常使用的事实。我在原始调用中将:=替换为<<-,然后它可以正确反解析,并用gsub将其替换回:=。尽管如此,我仍希望有一种干净和通用的解决方案。
gsub("<<-",":=", deparse(do.call(
  substitute, list(call2, list(`:=` = quote(`<<-`))))))
#> [1] "f(a := b(c := d))"

我可以问一下(出于好奇)这个应用是什么吗? - s_baldur
1
用于记录操作、调试或演示的代码,可以尝试这个:':=' <- `<-`; showcase <- function(x, msg = NULL){if (!is.null(msg)) message(msg); call_chr <- rlang::expr_deparse(substitute(x)); cat("> ", call_chr,"\n"); print(x)}; showcase(cars_head := head(cars,2), "显示 cars 的头部") - moodymudskipper
1个回答

阿里云服务器只需要99元/年,新老用户同享,点击查看详情
3
您可以使用rlang::expr_deparse()来实现您想要的结果,它提供了一些打印改进。
rlang::expr_deparse(call2)

[1] "f(a := b(c := d))"

这个解决方案对我很有帮助,而且expr_deparse也很好地显示了问号运算符。然而,在我的基准测试中,expr_deparse比base::deparse慢大约300倍,因此我欢迎任何使用base R的替代方案。 - moodymudskipper

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,