R 语言 do.call() 函数
描述:
do.call 根据名称或函数以及要传递给它的参数列表构造并执行函数调用。
语法:
do.call(what, args, quote = FALSE, envir = parent.frame())
参数:
what |
函数或命名要调用的函数的非空字符串。 |
args |
函数调用的参数列表。 args的names属性提供参数名称。 |
quote |
指示是否引用参数的逻辑值。 |
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. |
示例1:
> df
letter number sign
1 a 1 <
2 b 2 >
3 c 3 ^
4 d 4 <
5 e 5 >
6 f 6 ^
7 g 7 <
8 h 8 >
9 i 9 ^
> do.call(paste, c(df, sep=""))
[1] "a1<" "b2>" "c3^" "d4<" "e5>" "f6^" "g7<" "h8>" "i9^"
实例2:
> numbers <- list(10, 1:9)
> add <- function(x, y) {x + y}
> numbers[1]
[[1]]
[1] 10
> numbers[2]
[[1]]
[1] 1 2 3 4 5 6 7 8 9
> numbers[[1]] + numbers[[2]]
[1] 11 12 13 14 15 16 17 18 19
> add(numbers[[1]], numbers[[2]])
[1] 11 12 13 14 15 16 17 18 19
> do.call(add, numbers)
[1] 11 12 13 14 15 16 17 18 19
示例3:
> df <- data.frame("upper"=toupper(letters[1:7]),
"lower"=tolower(letters[1:7]),
"number"=1:7, stringsAsFactors=F)
> do.call(rbind, df)
[,1] [,2] [,3] [,4] [,5] [,6] [,7]
upper "A" "B" "C" "D" "E" "F" "G"
lower "a" "b" "c" "d" "e" "f" "g"
number "1" "2" "3" "4" "5" "6" "7"
> list1 <- list(df1, df2)
> list1
[[1]]
upper number
1 A 1
2 B 2
3 C 3
4 D 4
5 E 5
6 F 6
7 G 7
[[2]]
lower number
1 a 1
2 b 2
3 c 3
4 d 4
5 e 5
6 f 6
7 g 7
> do.call(cbind, list1)
upper number lower number
1 A 1 a 1
2 B 2 b 2
3 C 3 c 3
4 D 4 d 4
5 E 5 e 5
6 F 6 f 6
7 G 7 g 7
> do.call(merge, list1)
number upper lower
1 1 A a
2 2 B b
3 3 C c
4 4 D d
5 5 E e
6 6 F f
7 7 G g
按语:
do.call函数,应用在大数据时,速度相当不错。
非学无以广才,非志无以成学。