简体   繁体   中英

How to get match.call() from a united function?

I have three functions and one function is made out of the other two by using useMethod().

logReg <- function(x, ...) UseMethod("logReg")
logRec.numeric <- function(x, y) {
  print(x)
}
logReg.formula <- function(formula, data) {
  print(formula)
}

My functions are a bit more complex but does not matter for my question. I want logReg to give me additionaly the original function call as output (not the function call of logReg.numeric oder logReg.formula). My first try was:

logReg <- function(x, ...) {
  out <- list()
  out$call <- match.call()
  out
  UseMethod("logReg")
}

But it does not work. Can someone give me a hint how to solve my problem?

Try evaluating it explicitly. Note that this preserves the caller as the parent frame of the method.

logReg <- function(x, ...) {
  cl <- mc <- match.call()
  cl[[1]] <- as.name("logReg0")
  out <- structure(eval.parent(cl), call = mc)
  out
}

logReg0 <- function(x, ...) UseMethod("logReg0")
logReg0.numeric <- function(x, ...) print(x)
logReg0.formula <- function(x, ...) print(x)

result <- logReg(c(1,2))
## [1] 1 2

result
## [1] 1 2
## attr(,"call")
## logReg(x = c(1, 2))

Here's another way :

logReg <- function(x, ...) {
  logReg <- function(x, ...) UseMethod("logReg")
  list(logReg(x,...), call=match.call())
}

res <- logReg(1,2)
# [1] 1

res
# [[1]]
# [1] 1
# 
# $call
# logReg(x = 1, 2)
# 

You can make it work with atttibutes too if you prefer.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM