我們可以創建一個二維陣列來匹配兩個函式引數的組合嗎?
例如,如果我撰寫一個帶有 1 個引數的函式(除了資料輸入引數):
choose_procedure <- function(x, what_to_do) {
switch(what_to_do,
"mean" = {...}, # mean(x) or mean(x, na.rm = TRUE) or weighted.mean(x)
"median" = {...}, # median(x)
"square" = {...}, # x * x or x ^ 2
"unique" = {...}, # unique(x)
"log" = {...} # log(x) or log10(x)
)
}
我添加了行內注釋以暗示每個what_to_do輸入可能有多個選擇。
當what_to_do= 時"mean",應該是mean(x, na.rm = TRUE)還是mean(x, na.rm = FALSE)?同樣,當what_to_do= 時"log",應該是log(x)還是log10(x)?等等。
為了解決這個問題,我想向 引入另一個引數choose_procedure(),稱為"scenario"。所以如果呼叫的choose_procedure()是:
choose_procedure(x = mtcars$mpg, what_to_do = "log", scenario = "A")
然后它會執行log(mtcars$mpg)。
但如果電話是
choose_procedure(x = mtcars$mpg, what_to_do = "log", scenario = "B")
然后它會執行log10(mtcars$mpg)。
與僅僅是示例"log"并"scenario"描述了2×2陣列:
"what_to_do"有 2 個選項:log()或log10()"scenario"有兩個選擇:"A"或"B"
顯然,這可以用 4 個 if 陳述句(每個組合一個)來處理,但是如果我們有更多的組合(如choose_procedure()我打開的示例),將變得非常難以編程。
所以我有兩個問題:
- 我正在尋找可以擴展到任何n × n陣列的設定。
- 事實上,也許有一種方法可以推廣到超過n × n?例如,如果我們有 3 個引數:
"what_do_to","scenario","sub_scenario". 等等。
uj5u.com熱心網友回復:
choose_procedure <- function(x, FUN, ...){
if(...length()) FUN(x, ...)
else FUN(x)
}
x <- c(1,3,5,NA, 10)
choose_procedure(x, mean)
[1] NA
choose_procedure(x, mean, na.rm = TRUE)
[1] 4.75
choose_procedure(x, log)
[1] 0.000000 1.098612 1.609438 NA 2.302585
choose_procedure(x, log10)
[1] 0.0000000 0.4771213 0.6989700 NA 1.0000000
uj5u.com熱心網友回復:
這是有很多方法可以解決問題的方法之一,最好的方法很可能取決于您實際想要使用它的背景關系。但是,在您概述的情況下,我將采用以下方法它:
choose_procedure <- function(x, ...) {
# Define a table of options
choices <- tibble::tribble(
~what_to_do, ~scenario, ~result,
"mean", "A", mean,
"mean", "B", ~mean(., na.rm = TRUE),
"mean", "C", weighted.mean,
"median", "A", median,
"square", "A", ~. * .,
"square", "B", ~. ^ 2,
"unique", "A", unique,
"log", "A", log,
"log", "B", log10
)
# Filter the table down to the desired option
choice <- dplyr::filter(choices, ...)
# Stop if no options available
if (nrow(choice) == 0) {
stop("No such option available")
}
# Warn if multiple options available, and use first
if (nrow(choice) > 1) {
choice <- head(choices, 1)
warning("More than one option available, using first scenario")
}
# Transform any purrr-style lambda functions to normal functions
fun <- rlang::as_function(choice$result[[1]])
# Perform the calculation
fun(x)
}
choose_procedure(x = mtcars$mpg, what_to_do == "log", scenario == "B")
#> [1] 1.322219 1.322219 1.357935 1.330414 1.271842 1.257679 1.155336 1.387390
#> [9] 1.357935 1.283301 1.250420 1.214844 1.238046 1.181844 1.017033 1.017033
#> [17] 1.167317 1.510545 1.482874 1.530200 1.332438 1.190332 1.181844 1.123852
#> [25] 1.283301 1.436163 1.414973 1.482874 1.198657 1.294466 1.176091 1.330414
由reprex 包( v2.0.0 )于 2021 年 10 月 25 日創建
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/337939.html
