[英]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(). 我有三个函数,其中一个函数是使用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).
我希望logReg给我另外的原始函数调用作为输出(不是logReg.numeric或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. 如果您愿意,也可以使它与atttibutes一起使用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.