[英]Function to apply arbitrary functions in R
How would one implement in R the function apply.func(func, arg.list)
, which takes an arbitrary function func
and a suitable list arg.list
as arguments, and returns the result of calling func
with the arguments contained in arg.list
. 例如
apply.func(foo, list(x="A", y=1, z=TRUE))
相當於
foo(x="A", y=1, z=TRUE)
謝謝!
PS FWIW,相當於apply.func
的 Python 類似於
def apply_func(func, arg_list):
return func(*arg_list)
或者
def apply_func(func, kwarg_dict):
return func(**kwarg_dict)
或其一些變體。
我認為do.call
是您正在尋找的。 您可以通過?do.call
了解它。
人們如何使用do.call
的經典示例是將數據幀或矩陣rbind
在一起:
d1 <- data.frame(x = 1:5,y = letters[1:5])
d2 <- data.frame(x = 6:10,y = letters[6:10])
do.call(rbind,list(d1,d2))
這是另一個使用sum
的相當簡單的示例:
do.call(sum,list(1:5,runif(10)))
R 允許將函數作為 arguments 傳遞給函數。 這意味着您可以如下定義apply.func
(其中f
是 function 並且...
表示所有其他參數:
apply.func <- function(f, ...)f(...)
然后,您可以使用apply.func
並指定參數有意義的任何 function:
apply.func(paste, 1, 2, 3)
[1] "1 2 3"
apply.func(sum, 1, 2, 3)
[1] 6
但是,請注意以下可能不會產生您預期的結果,因為mean
將向量作為參數:
apply.func(mean, 1, 2, 3)
[1] 1
請注意,還有一個名為do.call
的基礎 R function 有效地做同樣的事情。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.