为什么match.call有用?

时间:2015-09-09 18:27:21

标签: r call

在某些R函数的主体中,例如lm,我看到了对match.call函数的调用。正如帮助页面所说,当在函数match.call中使用时,返回一个指定参数名称的调用;这对于将大量参数传递给另一个函数应该是有用的。

例如,在lm函数中,我们看到对函数model.frame的调用

function (formula, data, subset, weights, na.action, method = "qr", 
model = TRUE, x = FALSE, y = FALSE, qr = TRUE, singular.ok = TRUE, 
contrasts = NULL, offset, ...) 
{
cl <- match.call()
mf <- match.call(expand.dots = FALSE)
m <- match(c("formula", "data", "subset", "weights", "na.action", 
    "offset"), names(mf), 0L)
mf <- mf[c(1L, m)]

mf$drop.unused.levels <- TRUE
mf[[1L]] <- quote(stats::model.frame)
mf <- eval(mf, parent.frame())

为什么这比直接调用model.frame指定参数名称更有用呢?

function (formula, data, subset, weights, na.action, method = "qr", 
model = TRUE, x = FALSE, y = FALSE, qr = TRUE, singular.ok = TRUE, 
contrasts = NULL, offset, ...) 
{
mf <- model.frame(formula = formula, data = data,
                  subset = subset, weights = weights, subset = subset) 

请注意match.call还有另一个我没有讨论的用法,将调用存储在结果对象中。

2 个答案:

答案 0 :(得分:7)

与此相关的一个原因是match.call在不对其进行评估的情况下捕获调用语言,在这种情况下,它允许lm将某些“缺失”变量视为“可选” 。考虑:

lm(x ~ y, data.frame(x=1:10, y=runif(10)))

Vs的:

lm2 <- function (
  formula, data, subset, weights, na.action, method = "qr", 
  model = TRUE, x = FALSE, y = FALSE, qr = TRUE, singular.ok = TRUE, 
  contrasts = NULL, offset, ...
) {
  mf <- model.frame(
    formula = formula, data = data, subset = subset, weights = weights
  ) 
}
lm2(x ~ y, data.frame(x=1:10, y=runif(10)))
## Error in model.frame.default(formula = formula, data = data, subset = subset,  :
##   invalid type (closure) for variable '(weights)'

lm2中,由于weights“缺失”,但您仍然在weights=weights中使用它,R会尝试使用stats::weights功能,这显然不是预期的。您可以在致电model.frame之前通过测试缺失来解决这个问题,但此时match.call开始看起来非常好。看看如果我们debug通话会发生什么:

debug(lm2)
lm2(x ~ y, data.frame(x=1:10, y=runif(10)))
## debugging in: lm2(x ~ y, data.frame(x = 1:10, y = runif(10)))
## debug at #5: {
##     mf <- model.frame(formula = formula, data = data, subset = subset,
##         weights = weights)
## }
Browse[2]> match.call()
## lm2(formula = x ~ y, data = data.frame(x = 1:10, y = runif(10)))

match.call根本不涉及缺失的参数。

你可以说可选参数应该通过默认值显式选择,但这不是这里发生的事情。

答案 1 :(得分:-1)

这是一个例子。在其中,calc_1是一个函数,带有许多要加和乘的数字参数。它将这项工作委派给calc_2,它是一个使用大多数这些参数的辅助函数。但是calc_2还需要一些额外的参数(q到t),而calc_1不能从其实际参数中提供这些参数。而是将它们作为附加项传递。

如果写出对calc_2的调用,那真是太可怕了,以显示calc_1传递的所有内容。因此,我们假设如果calc_1和calc_2共享一个形式参数,则它们将使用相同的名称。这样就可以编写一个调用程序,该调用程序可以计算出calc_1可以传递给calc_2的参数,构造可以执行此调用的调用,并提供额外的值来完成该调用。下面代码中的注释应该使这一点变得清楚。

顺便说一句,仅对于%>%和我定义了calc_2的str_c才需要库“ tidyverse”,而对于一个断言则仅需要库“ assertthat”。 (尽管在一个现实的程序中,我会使用断言来检查参数。)

这是输出:

> calc_1( a=1, b=11, c=2, d=22, e=3, f=33, g=4, h=44, i=5, j=55, k=6
+       , l=66, m=7, n=77, o=8, p=88 
+       )
[1] "87654321QRST"

这是代码:

library( tidyverse )
library( rlang )
library( assertthat )


`%(%` <- call_with_extras
#
# This is the operator for calling
# a function with arguments passed
# from its parent, supplemented 
# with extras. See call_with_extras()
# below.


# A function with a very long
# argument list. It wants to call
# a related function which takes
# most of these arguments and
# so has a long argument list too.
# The second function takes some
# extra arguments.
#
calc_1 <- function( a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p )
{
  calc_2 %(% list( t = "T", q = "Q", s = "S", r = "R" )
  #
  # Call it with those extras, passing 
  # all the others that calc_2() needs
  # as well. %(% is my function for
  # doing so: see below.
}


# The function that we call above. It
# uses its own arguments q to t , as
# well as those from calc_1() .
#
calc_2 <- function( a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t )
{
  ( a + c * 10 + e * 100 + g * 1000 + i * 10000 + k * 100000 +
  m * 1000000 + o * 10000000 ) %>%
  str_c( q, r, s, t )
} 


# Calls function f2 . Passes f2 whichever
# arguments it needs from its caller. 
# Corresponding formals should have the
# same name in both. Also passes f2 extra
# arguments from the named list extra. 
# The names should have the same names as
# corresponding formals of f2 .
#
call_with_extras <- function( f2, extras )
{   
  f1_call <- match.call( sys.function(1), sys.call(1) )  
  # A call object.

  f1_actuals <- as.list( f1_call %>% tail(-1) ) 
  # Named list of f1's actuals.

  f1_formals <- names( f1_actuals )
  # Names of f1's formals.

  f2_formals <- names( formals( f2 ) )
  # Names of f2's formals.

  f2_formals_from_f1 <- intersect( f2_formals, f1_formals )
  # Names of f2's formals which f1 can supply.

  f2_formals_not_from_f1 <- setdiff( f2_formals, f1_formals )
  # Names of f2's formals which f1 can't supply.

  extra_formals <- names( extras ) 
  # Names of f2's formals supplied as extras.

  assert_that( setequal( extra_formals, f2_formals_not_from_f1 ) )
  # The last two should be equal.

  f2_actuals_from_f1 <- f1_actuals[ f2_formals_from_f1 ]
  # List of actuals which f1 can supply to f2.

  f2_actuals <- append( f2_actuals_from_f1, extras )
  # All f2's actuals.

  f2_call <- call2( f2, !!! f2_actuals )
  # Call to f2.

  eval( f2_call )
  # Run it.
}


# Test it.
#
calc_1( a=1, b=11, c=2, d=22, e=3, f=33, g=4, h=44, i=5, j=55, k=6
      , l=66, m=7, n=77, o=8, p=88 
      )