【发布时间】:2020-06-20 13:57:28
【问题描述】:
问题的最终目标是使用r 对语言的计算来构造以下未评估调用,其中list、a_name 和50L 由参数提供.
list(a_name = 50L)
内部看起来像
str(quote(list(a_name = 50L)))
# language list(a_name = 50L)
str(as.list(quote(list(a_name = 50L))))
#List of 2
# $ : symbol list
# $ a_name: int 50
我会将我的变量放在一个列表中,以便进一步的代码更清晰。
params = list(my_fun = as.name("list"), my_name = "a_name", my_value = 50L)
# What I tried so far?
# 1. The first thing that one would try
substitute(my_fun(my_name = my_value),
params)
#list(my_name = 50L) ## `my_name` was not substituted!
# 2. Workaround get the same output, but only after `setNames` call evaluation, so doesn't really answer the question about constructing specific call
substitute(setNames(my_fun(my_value), my_name), ## alternatively could be `structure(..., names=my_name)`
params)
#setNames(list(50L), "a_name")
# 3. Another workaround, not really computing on the language but parsing, and integer L suffix is gone!
with(expr = parse(text=paste0(my_fun, "(", my_name, " = ", my_value, ")"))[[1L]],
data = params)
#list(a_name = 50)
# 4. Working example using rlang
with(expr = rlang::call2(my_fun, !!my_name := my_value),
data = params)
#list(a_name = 50L)
base r 中是否有任何方法来构造所需的调用? 基本上可以得到与 rlang 完全相同的输出,但使用 base r。
请注意,此问题不是 this 的重复,后者严格要求 rlang 解决方案。这个问题要求一种使用基础r 来实现它的方法。如果没有办法实现它,我也想知道。谢谢。
【问题讨论】:
-
str2lang(paste("", "list", " (", "a_name", " = ", "50L", ")"))能给你想要的吗? -
@jay.sf
str2lang只是parse的特殊版本,所以并不比示例 3 好。
标签: r r r r r metaprogramming rlang