在R

2017-09-13 105 views
0

中使用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) 

我的问题是:

  1. 是选项3,执行本次评估
  2. 发生了什么

编辑

的解释最好/最简单的方法在阅读@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”。

回答

3

我会尝试回答问题1.
我相信,执行这种评估的最好和最简单的方法是不需要任何形式的评估技术。直接调用函数通常是可行的。使用你的例子,尝试以下。

EvaluateThis4 <- mean # simple 

MyFunc4 <- function(vector, TheFunction){ 
    print(TheFunction) 
    TheFunction(vector) # just call it with the appropriate argument(s) 
} 

MyFunc4(1:4, EvaluateThis4) 
function (x, ...) 
UseMethod("mean") 
<bytecode: 0x000000000489efb0> 
<environment: namespace:base> 
[1] 2.5 

有在基地R.这样的例子比如approxfunecdf,你可以直接在代码中使用,以进行后续的计算都返回功能。这就是为什么我定义了这样的EvaluateThis4
对于使用函数作为参数的函数,有优化函数,当然,还有*apply,byave

至于问题2,我必须承认我完全无知。

+0

感谢您阅读后的答案我意识到我没有问好我的问题。查看编辑。如果有一个类似于你的第一个解决方案的解决方案会很好。谢谢您的帮助 –