gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-05 03:48:19 25 4
gpt4 key购买 nike

如果您能就这个小难题提供任何帮助,我们将不胜感激。

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

我已经尝试了所有我能想到的方法来将字符串 'apply.quarterly' 转换为 mutate_fun 参数接受的对象 apply.quarterly。注释行是我失败的尝试。

最终,我想将这个概念扩展到其他参数,即 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 = 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 = rlang::as_quosure('apply.quarterly'),
# mutate_fun = enexpr('apply.quarterly'),
# mutate_fun = enexprs('apply.quarterly'),
# mutate_fun = ensym('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'),
# 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"
)
)

关于R如何将一个函数作为字符串传递给另一个函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64452369/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com