R如何在另一个函数内将函数作为字符串传递

问题描述

在这个小难题上的任何帮助将不胜感激。

我正在尝试将参数从tq_transmute包传递给tidyquant函数;参数的值是一个函数,但是我想将其作为字符串传递(超出下面示例的范围,我将通过Shiny selectInput传递它)。

我已经尽力尝试将字符串'apply.quarterly'转换为apply.quarterly参数接受的对象mutate_fun。带注释的行是我失败的尝试。

最终,我想将此概念扩展到其他参数,即FUN = maxFUN = ‘max’

library(tidyverse)
library(tidyquant)
library(rlang)

FANG %>%
  group_by(symbol) %>%
  tq_transmute(select     = adjusted,mutate_fun = apply.quarterly,# mutate_fun = sym('apply.quarterly'),# mutate_fun = syms('apply.quarterly'),# mutate_fun = !!sym('apply.quarterly'),# mutate_fun = !!!sym('apply.quarterly'),# mutate_fun = eval(parse('apply.quarterly')),# mutate_fun = eval(substitute('apply.quarterly')),# mutate_fun = enquo('apply.quarterly'),# mutate_fun = expr(!!enquo('apply.quarterly')),# mutate_fun = quo('apply.quarterly'),# mutate_fun = enquos('apply.quarterly'),# mutate_fun = enquote('apply.quarterly'),# mutate_fun = quote('apply.quarterly'),# mutate_fun = substitute('apply.quarterly'),# mutate_fun = parse('apply.quarterly'),# mutate_fun = ensym('apply.quarterly'),# mutate_fun = rlang::as_function('apply.quarterly'),# mutate_fun = rlang::as_closure('apply.quarterly'),# mutate_fun = rlang::as_quosure('apply.quarterly'),# mutate_fun = enexpr('apply.quarterly'),# mutate_fun = enexprs('apply.quarterly'),# mutate_fun = ensyms('apply.quarterly'),# mutate_fun = eval_tidy('apply.quarterly'),# mutate_fun = exprs('apply.quarterly'),# mutate_fun = expr_deparse('apply.quarterly'),# mutate_fun = expr_label('apply.quarterly'),# mutate_fun = expr_label(substitute('apply.quarterly')),# mutate_fun = expr_label(quote('apply.quarterly')),# mutate_fun = parse_expr('apply.quarterly'),# mutate_fun = quasiquotation('apply.quarterly'),# mutate_fun = quotation('apply.quarterly'),FUN        = max,col_rename = "max.close")

解决方法

您可以使用blast()进行即时报价的准报价

blast <- function(expr,env = caller_env()) {
  eval_bare(enexpr(expr),env)
}

blast(list(!!!1:3))
#> [[1]]
#> [1] 1
#>
#> [[2]]
#> [1] 2
#>
#> [[3]]
#> [1] 3

然后

myfun <- "apply.quarterly"

blast(
  FANG %>%
    group_by(symbol) %>%
    tq_transmute(
      select = adjusted,mutate_fun = !!sym(myfun),FUN = max,col_rename = "max.close"
    )
)
,

由于某种原因,功能似乎有点挑剔。一种方法是更改​​呼叫,然后取消该呼叫。例如

myfun <- "apply.quarterly"
bquote(FANG %>%
  group_by(symbol) %>%
  tq_transmute(select     = adjusted,mutate_fun = .(as.name(myfun)),FUN        = max,col_rename = "max.close")) %>% 
  eval()

或者如果您更喜欢rlang语法

myfun <- "apply.quarterly"
quo(FANG %>%
         group_by(symbol) %>%
         tq_transmute(select     = adjusted,col_rename = "max.close")) %>% 
  eval_tidy()

请注意,我们必须将整个表达式视为rlang级。除非专门为处理tq_transmute之类的rlang功能编写了!!函数,否则默认情况下它们将无法工作。

,

您可以使用 get 从带有函数名称的字符串中获取函数。例如,下面的作品:

s <- get("sum")
s(c(1,2,3))

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...