中使用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」。
感謝您閱讀後的答案我意識到我沒有問好我的問題。查看編輯。如果有一個類似於你的第一個解決方案的解決方案會很好。謝謝您的幫助 –