我有一个用例,其中我想将命令行评估args
为函数名。例如,
r_script.R print --number 2
我将以r包docopt
为例。参数通常由其自己的名称索引,例如,args$print
引用字符串value "print"
。实际的R代码就是
if (args$print){
if (args$number){
# call print()
print(as.numeric(args$number))
}
}
当我有一长串的函数(例如)时print
,我会写一个庞大的函数if-else-loop
来应对它,并且很快就会变得乏味。
是否有一种方法,例如使用quosure
,eval
或类似方法替换此逻辑,以便我仅编写几行代码即可完成工作?
例如,理想的逻辑是
func_enquo -> enquo(args$func) # func is in place of `print`
func_enquo(value) # what matters is the print argument here.
我已经尝试enquo
过编写包装函数,但没有成功;我尝试了eval_tidy
那只是徒劳(代码无效)。
据我了解,您想使用第一个参数作为函数名称吗?然后尝试以get()
某种方式使用:
do_something <- function(fct, arg) {
get(fct)(arg)
}
do_something("print", "Hello")
#>[1] "Hello"
do_something("mean", 1:5)
#> 3
请注意,您必须小心传入的内容。然后,您可以将参数称为args [1],而不是args $ print,如果它始终是第一个这样的参数:
func_enquo -> get(args[1]) # func is in place of `print`
func_enquo(value) # what matters is the print argument here.
有帮助吗?
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句