2015-11-02 75 views
1

假設我寫了接受另一個函數作爲參數的函數:檢查作爲參數在R功能通過一個函數的名稱

fct1 <- function(FUN) { 
    # If FUN is rnorm, then do this. 
    # If FUN is rbeta, then do this. 
    } 

我應該如何檢查FUN是否rnorm

我知道我能做到這一點通過toString()功能通過as.list()轉換到一個列表,然後強制其爲字符串:

toString(as.list(rnorm)) 

結果是:

", 0, 1, .Call(C_rnorm, n, mean, sd)" 

我可以再檢查C_rnorm的內容。

但我認爲這不是一個好的解決方案。我也在某處(我不記得源代碼)強制關閉一個列表,然後字符串可能只是爲了向後兼容,並不鼓勵。

我也想過body()。例如,

body(rnorm) 

結果是:

.Call(C_rnorm, n, mean, sd) 

然而,那我該怎麼檢查是否C_rnorm是調用內部?我試圖用as.list()然後toString()

toString(as.list(body(rnorm))) 

這是結果:

".Call, C_rnorm, n, mean, sd" 

然而,這是一個好的做法呢?

回答

2

您可以使用match.call

fct1 <- function(FUN) { 
    called <- match.call()$FUN 
    if(called == "rnorm") { 
    return("Passed rnorm") 
    } else { 
    return("Not rnorm") 
    } 

} 

fct1(rnorm) 
# [1] "Passed rnorm" 
fct1(rlnorm) 
# [1] "Not rnorm" 
+0

謝謝!有用! 我想知道它是如何工作的。我檢查過,例子中match.call()$ FUN'的'type'是'symbol','class'是'name'。我認爲(不正確),它不會工作,因爲'match.call()$ FUN'不是一個字符串。 被調用的字符串比較調用==「rnorm」'嗎? – sfcheung

+0

@sfcheung是的,就是這麼多。名稱/符號幾乎是表示對象的字符串。幫助頁'?name'有一些解釋。 – Molx

相關問題