Schneeflocke
Schneeflocke

Reputation: 43

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?

Upvotes: 4

Views: 67

Answers (2)

G. Grothendieck
G. Grothendieck

Reputation: 269481

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))

Upvotes: 1

moodymudskipper
moodymudskipper

Reputation: 47300

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.

Upvotes: 1

Related Questions