do.call
這個函數(shù)是我在搜索問題時會看到別人經(jīng)常使用的一個函數(shù)厚棵,心生好奇,這次來看看它的用法蔼紧。
從文檔來看婆硬,do.call
可以通過名字構建和執(zhí)行函數(shù),并且將參數(shù)以列表的形式傳入奸例。
Description
do.call constructs and executes a function call from a name or a function and a list of arguments to be passed to it.
Usage
do.call(what, args, quote = FALSE, envir = parent.frame())
Arguments
what
either a function or a non-empty character string naming the function to be called.
args
a list of arguments to the function call. The names attribute of args gives the argument names.
quote
a logical value indicating whether to quote the arguments.
envir
an environment within which to evaluate the call. This will be most useful if what is a character string and the arguments are symbols or quoted expressions.
顯然彬犯,前兩個參數(shù)很重要,確定了該函數(shù)的一般用法查吊,后兩個參數(shù)涉及一些執(zhí)行引用與環(huán)境的問題谐区,這方面我懂的不多,不過基本也用不到逻卖。
下面通過例子學習下使用宋列。
例子
# 生成一個復數(shù)序列
do.call("complex", list(imag = 1:3))
## [1] 0+1i 0+2i 0+3i
# 如果我們有一個列表(比如數(shù)據(jù)框)
# 我們需要使用c()添加更多的參數(shù)
tmp <- expand.grid(letters[1:2], 1:3, c("+", "-"))
tmp
## Var1 Var2 Var3
## 1 a 1 +
## 2 b 1 +
## 3 a 2 +
## 4 b 2 +
## 5 a 3 +
## 6 b 3 +
## 7 a 1 -
## 8 b 1 -
## 9 a 2 -
## 10 b 2 -
## 11 a 3 -
## 12 b 3 -
do.call("paste", c(tmp, sep=""))
## [1] "a1+" "b1+" "a2+" "b2+" "a3+" "b3+" "a1-" "b1-" "a2-" "b2-" "a3-"
## [12] "b3-"
#do.call("paste", list(tmp, sep=""))
do.call(paste, list(as.name("A"), as.name("B")), quote = TRUE)
## [1] "A B"
do.call(paste, list(as.name("A"), as.name("B")), quote = TRUE)
## [1] "A B"
# 這個例子中,A箭阶、B被轉換為了符號對象虚茶,如果不quote起來就會報錯
#do.call(paste, list(as.name("A"), as.name("B")), quote = FALSE)
# 當然你如果直接使用下面這個語句結果是一樣的戈鲁,不過這里是介紹quote的用法
do.call(paste, list("A", "B"))
## [1] "A B"
從哪里尋找對象的例子:
A <- 2
f <- function(x) print(x ^ 2)
env <- new.env()
assign("A", 10, envir = env)
assign("f", f, envir = env)
f <- function(x) print(x)
f(A)
## [1] 2
# 使用當前環(huán)境函數(shù)與變量
do.call("f", list(A))
## [1] 2
# 使用env環(huán)境函數(shù)與當前環(huán)境變量
do.call("f", list(A), envir = env)
## [1] 4
# 使用當前環(huán)境函數(shù)與變量
do.call(f, list(A), envir = env)
## [1] 2
# 使用env環(huán)境函數(shù)與env環(huán)境變量
do.call("f", list(quote(A)), envir = env)
## [1] 100
# 使用當前環(huán)境函數(shù)與env環(huán)境變量
do.call(f, list(quote(A)), envir = env)
## [1] 10
# 使用env環(huán)境函數(shù)與env環(huán)境變量
do.call("f", list(as.name("A")), envir = env)
## [1] 100
eval(call("f", A))
## [1] 2
eval(call("f", quote(A)))
## [1] 2
eval(call("f", A), envir = env)
## [1] 4
eval(call("f", quote(A)), envir = env)
## [1] 100
上面例子多仇参,需要仔細揣摩參數(shù)變化后結果的變化。首先在新環(huán)境創(chuàng)建的函數(shù)對象是打印輸入的平方婆殿,A
是10诈乒。
call
函數(shù)用來創(chuàng)建和測試對象,不過看起來用法與quote()
類似婆芦,將東西先存起來不執(zhí)行怕磨,等后續(xù)調用。
A <- 10.5
wait <- call("round", A)
eval(wait)
## [1] 10