在R

2017-09-13 124 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

感謝您閱讀後的答案我意識到我沒有問好我的問題。查看編輯。如果有一個類似於你的第一個解決方案的解決方案會很好。謝謝您的幫助 –