[英]Matching vector of default values using match.arg() with or without error [R]
我想編寫一個函數,將兩種不同的統計方法之一應用於其輸入。 在這個過程中,我注意到了一些我不理解的不同功能的行為。 我想寫的函數應該具有以下屬性:
基本上,我希望函數的行為與R中的cor
一樣。在那里,你有一個默認值method = c("pearson", "kendall", "spearman")
,如果method
不是,則函數計算出Pearson相關性指定。 如果用戶一次請求多個方法,則該函數返回錯誤。
通過查看cor
,這似乎是使用match.arg(method)
。 此行為如下所示:
x <- y <- 1:5
cor(x, y, method="pearson")
# = 1
cor(x, y, method="kendall")
# = 1
cor(x, y, method=c("pearson","kendall"))
# gives an error
我嘗試編寫自己的函數,也使用match.arg(method)
,但我意識到結果有些不同。 即使為method
選擇向量,該函數也不會以錯誤終止,而是返回第一個方法的結果。
這在這里說明:
myfun <- function(x, method=c("add","multiply")){
method <- match.arg(method)
if(method=="add") return(sum(x))
if(method=="multiply") return(prod(x))
}
x <- 1:5
myfun(x, method="add")
# = 15
myfun(x, method="multiply")
# = 120
myfun(x, method=c("add","multiply"))
# = 15
我不明白這種行為,如果你能幫助我,我會很高興的。 從我在谷歌的嘗試中,我意識到它可能與非標准評估有關,但我還不能把兩個和兩個放在一起。
在此先感謝,非常感謝您的幫助!
干杯!
編輯:
我也可以重新說出我的問題:
沒有什么強大的巫術cor
做它返回時Pearson相關method
沒有提供,但是當它返回一個錯誤method = c("pearson", "kendall", "spearman")
明確規定?
如果match.arg
choices
和args
相同,則返回第一個元素。 否則arg
必須是長度1.來自match.arg
:
由於默認參數匹配會將arg設置為選項,因此允許將此作為“length one除非:many.ok為TRUE”規則的例外,並返回第一個元素。
match.arg(c("pearson", "kendall", "spearman"), c("pearson", "kendall", "spearman"))
## [1] "pearson"
match.arg(c("pearson", "kendall"), c("pearson", "kendall", "spearman"))
## Error in match.arg(c("pearson", "kendall"), c("pearson", "kendall", "spearman")) :
## 'arg' must be of length 1
您可以使用偽參數獲得所需的行為:
myfun <- function(x, method=c("add","multiply","other.return.error")){
method <- match.arg(method)
if("other.return.error" %in% method) stop("this option should not be used")
if(method=="add") return(sum(x))
if(method=="multiply") return(prod(x))
}
@shadow回答了主要問題(見上文)。
獲得myfun
所需行為的另一種方法是執行檢查是否提供method
,如果顯式提供了多個元素,則打印錯誤。
myfun <- function(x, method=c("add","multiply")){
if(!missing(method) & length(method)>1) stop("Only one 'method' allowed.")
method <- match.arg(method)
if(method=="add") return(sum(x))
if(method=="multiply") return(prod(x))
}
x <- 1:5
myfun(x)
# = 15
myfun(x, method="add")
# = 15
myfun(x, method="multiply")
# = 120
myfun(x, method=c("add","multiply"))
# gives error
這繞過了@shadow指出的match.arg
的異常,通過該異常向函數提供向量可能不會導致錯誤。 相反,這個錯誤立即給出。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.