中使用quo()计算另一个函数中的一个参数的函数我已经创建了一个函数,它将另一个函数作为参数,参数函数将一些对象(在示例中是一个向量)作为参数,它是由原始功能提供。以正确的方式进行函数调用一直具有挑战性。在阅读Programming with dplyr后,下面是我使用的三种方法。 只有选项三的作品,在R
我想知道这实际上是评估函数中的函数的最佳方法。
library(dplyr);library(rlang)
#Function that will be passed as an arguement
EvaluateThis1 <- quo(mean(vector))
EvaluateThis2 <- ~mean(vector)
EvaluateThis3 <- quo(mean)
#First function that will recieve a function as an argument
MyFunc <- function(vector, TheFunction){
print(TheFunction)
eval_tidy(TheFunction)
}
#Second function that will recieve a function as an argument
MyFunc2 <- function(vector, TheFunction){
print(TheFunction)
quo(UQ(TheFunction)(vector)) %>%
eval_tidy
}
#Option 1
#This is evaluating vector in the global environment where
#EvaluateThis1 was captured
MyFunc(1:4, EvaluateThis1)
#Option 2
#I don't know what is going on here
MyFunc(1:4, EvaluateThis2)
MyFunc2(1:4, EvaluateThis2)
#Option 3
#I think this Unquotes the function splices in the arguement then
#requotes before evaluating.
MyFunc2(1:4, EvaluateThis3)
我的问题是:
- 是选项3,执行本次评估
- 发生了什么
编辑
的解释最好/最简单的方法在阅读@Rui Barradas后,我非常清楚和简洁的回答,我意识到我其实正在努力工作Ø成才类似下面这是我没有管理,使工作用锐的方法,但使用环境设置
OtherStuff <-c(10, NA)
EvaluateThis4 <-quo(mean(c(vector,OtherStuff), na.rm = TRUE))
MyFunc3 <- function(vector, TheFunction){
#uses the captire environment which doesn't contain the object vector
print(get_env(TheFunction))
#Reset the enivronment of TheFunction to the current environment where vector exists
TheFunction<- set_env(TheFunction, get_env())
print(get_env(TheFunction))
print(TheFunction)
TheFunction %>%
eval_tidy
}
MyFunc3(1:4, EvaluateThis4)
功能是当前环境不捕捉环境中评估解决。由于在该环境中没有对象“OtherStuff”,所以在全局环境中搜索父环境时发现“OtherStuff”。
感谢您阅读后的答案我意识到我没有问好我的问题。查看编辑。如果有一个类似于你的第一个解决方案的解决方案会很好。谢谢您的帮助 –