Behavior of do.call() in the presence of arguments without defaults

元气小坏坏 提交于 2019-12-05 13:14:18

In a regular function call ... captures arguments by position, partial match and full match:

f <- function(...) g(...)
g <- function(x, y, zabc) c(x = x, y = y, zabc = zabc)

f(1, 2, 3)
# x    y zabc 
# 1    2    3     
f(z = 3, y = 2, 1)
# x    y zabc 
# 1    2    3     

do.call behaves in exactly the same way except instead of supplying the arguments directly to the function, they're stored in a list and do.call takes care of passing them into the function:

do.call(f, list(1, 2, 3))
# x    y zabc 
# 1    2    3     
do.call(f, list(z = 3, y = 2, 1))
# x    y zabc 
# 1    2    3     

I think it is worth stressing that the names of the list elements do matter. Hadley mentioned it, but it can be an annoyance. Consider the next example:

x <- rnorm(1000)
y <- rnorm(1000)
z <- rnorm(1000) + 0.2

Models <- list()
Models$xy <- lm(z~x)
Models$yz <- lm(z~y)

# This will fail, because do.call will not assign anything to the argument "object" of anova
do.call(anova, Models)
# This won't
do.call(anova, unname(Models))

do.call passes the first element of the list to the first argument:

fun <- function(x,...) {
  print(paste0("x=",x))

  list(x, ...)
}

do.call(fun, list(1,2))
# [1] "x=1"
# [[1]]
# [1] 1
# 
# [[2]]
# [1] 2
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!