2017-10-18 32 views
0

我仍試圖理解R中的問題,但我不明白爲什麼下面的函數中的替換失敗。如何在自定義函數中使用rlang :: UQS中的變量?

my.toggle <- function(toggle) { 
    if (toggle) { 
    print("yes") 
    } else { 
    print("no") 
    } 
} 

fn.args <- list(toggle = T) 
my.toggle(rlang::UQS(fn.args)) # fails 
# Error in if (toggle) { : argument is not interpretable as logical 

rlang::quo(my.toggle(rlang::UQS(fn.args))) # but this is the right function call 
# <quosure: global> 
# ~my.toggle(toggle = TRUE) 

好像叫my.toggle(rlang::UQS(fn.args))應相當於my.toggle(toggle = T)(事實上,這是當你在包裝的quo函數調用你會得到什麼),但該函數不正確執行。我究竟做錯了什麼?

回答

0

你必須評估你的quosure,像這樣:

library(rlang) 

eval_tidy(quo(my.toggle(UQS(fn.args)))) 

[1] "yes" 
[1] "yes" 

(爲什麼它打印兩次這是print()一種假象:print正常返回其參數,無形看來評估。隱式地切換可見性,所以返回值會再次打印。如果您只是將print("yes")替換爲(print("yes"))(使用parens手動切換可見性),則行爲與my.toggle(toggle = TRUE)再次保持一致。我不會擔心它太多)。

至於爲什麼你會收到錯誤:UQS()返回一個列表,具體爲:a Dotted pair list of 1:。你可以用my.toggle(UQS(fn.args)[["toggle"]])來破解。

相關問題