[R的基址替换为函数调用的参数名称

问题描述 投票:1回答:1

问题的最终目标是使用语言的R计算来构造以下unvaluated调用,其中从参数提供lista_name50L

list(a_name = 50L)

# which internally looks like
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中有什么方法可以构造所需的调用?

[请注意,此Q不是严格要求this解决方案的rlang的重复项。这个Q要求一种使用基数R实现它的方法。如果没有办法实现,我也想知道。谢谢。

r metaprogramming rlang
1个回答
0
投票

[我假设问题是如何获取输入params并执行以my_fun组件的名称使用params的其他组件作为参数的函数。在这种情况下,请使用do.call

do.call(as.character(params$my_fun), params[-1])

as.call

eval(as.call(params))

这些都给:

$my_name
[1] "a_name"

$my_value
[1] 50
© www.soinside.com 2019 - 2024. All rights reserved.