问题的最终目标是使用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)
在基础的r中有没有构建必需调用的方法? 基本上,要获得与rlang
方式完全相同的输出,但使用基础r。
请注意,这个问题不是this的重复,该问题严格要求使用rlang
解决方案。这个问题要求以基础r的方式实现它。如果没有办法实现,我也想知道。谢谢。
str2lang(paste("", "list", " (", "a_name", " = ", "50L", ")"))
能够得到你想要的结果吗? - jay.sf