我正在為我的包撰寫函式,并且在傳遞附加引數時遇到了麻煩,因為...
我有一個“背景”函式,在 MRE 中我從下面呼叫它(change_font()),例如在示例中使用 2 個引數(fontsize和font)。
現在我撰寫了第二個函式,test()在示例中呼叫,并希望它具有選項(帶有...)來傳遞應該傳遞給的附加引數change_font()。
問題
只要僅包含 change_font 函式中使用的引數,它就可以change_font(...)從內部使用。我嘗試在串列中進行轉換并過濾它以查找不起作用的函式中的引數。test()......change_font()
是否有一種方便的方法(在測驗函式內部)從 ... 引數中選擇 change_font 所需的引數?
MRE
change_font <- function(fontsize = 12, font = "Times New Roman") {
print(paste("Font is set to:", font))
print(paste("Fontsize is set to:", fontsize))
}
test <- function(a = "ba", ...) {
# change_font(...)
# Works when only useable parameters are passed
# - However Fails when non-arguments from change_font are passed, e.g. test2 = 42
# DID notwork
# print(typeof(...))
# print(class(...))
# Trying to filter unused additional args
additional_args <- list(...)[c("font","fontsize")]
print(additional_args)
# Filtering works fine. List only contains desired arguments
change_font(additional_args)
# if (hasArg(fontsize)) fontsize <- additional_args[["fontsize"]]
# print(hasArg(font))
# if (hasArg(font)) font = additional_args[["font"]]
# # Try 2
# change_font(
# font = font,
# fontsize = fontsize
#
# )
}
change_font()
#> [1] "Font is set to: Times New Roman"
#> [1] "Fontsize is set to: 12"
test(font = "ABC", fontsize = 111)
#> $font
#> [1] "ABC"
#>
#> $fontsize
#> [1] 111
#>
#> [1] "Font is set to: Times New Roman"
#> [1] "Fontsize is set to: ABC" "Fontsize is set to: 111"
test(font = "ABC", fontsize = 111, test2 = 42)
#> $font
#> [1] "ABC"
#>
#> $fontsize
#> [1] 111
#>
#> [1] "Font is set to: Times New Roman"
#> [1] "Fontsize is set to: ABC" "Fontsize is set to: 111"
由reprex 包于 2022-01-24 創建(v2.0.1)
uj5u.com熱心網友回復:
最好的方法是將點作為引數,change_font在函式體中被忽略。
比較一個change_fonts沒有點作為引數的最小示例:
change_font <- function(fontsize = 12, font = "Times New Roman") {
print(paste("Font is set to:", font))
print(paste("Fontsize is set to:", fontsize))
}
test <- function(a = "ab", ...) {
change_font(...)
}
如果我們將無法識別的引數傳遞給,這將導致錯誤test:
test(fontsize = 14, color = "red")
#> Error in change_font(...): unused argument (color = "red")
但是看看當我們在 中包含點作為引數時會發生什么change_font:
change_font <- function(fontsize = 12, font = "Times New Roman", ...) {
print(paste("Font is set to:", font))
print(paste("Fontsize is set to:", fontsize))
}
test(fontsize = 14, color = "red")
#> [1] "Font is set to: Times New Roman"
#> [1] "Fontsize is set to: 14"
這里發生的情況是,在這兩種情況下color = "red"都作為引數傳遞給change_font,但在第二個示例中,不是得到color引數無法識別的錯誤,而是被解釋為“點引數”之一,因此不會觸發一個錯誤。
這是 R 中非常常用的策略。
由reprex 包于 2022-01-24 創建(v2.0.1)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/421383.html
標籤:
上一篇:將n個字串陣列轉換為符號*
下一篇:PHP類函式
