我有一个名为的泛型函数foo
.它在类上的操作方式不同bar
,baz
但有一些共享预处理只需要执行一次.什么是惯用的R方式来实现这一目标?
在我下面的愚蠢示例中,我希望将传递给对象的对象乘以10.然而,当调用该方法时,原始值将打印到控制台.我已阅读语言定义并知道以下模式不起作用.我的问题是:在调用方法之前,我应该在何处或如何处理泛型参数的共享处理?
a <- structure(1:5, class="bar")
b <- structure(6:10, class="baz")
foo <- function(x) {
x <- x * 10 # where should shared preprocessing go?
UseMethod("foo")
}
foo.bar <- function(x) {
cat("Foo!", x)
}
foo.baz <- function(x) {
cat("Baz!", x)
}
# does not propagate the operations carried out `foo`
foo(a)
foo(b)
Run Code Online (Sandbox Code Playgroud)
G. *_*eck 13
1)在实际泛型更改之上的层foofoo
执行初步代码并调用foo_
新的泛型,如图所示.重命名foo.bar
,并foo.baz
以foo_.bar
和foo_.baz
分别让我们剩下的(也加入了新行的例子):
foo <- function(x) {
x <- x * 10
foo_(x)
}
foo_ <- function(x) UseMethod("foo_")
foo_.bar <- function(x) cat("Foo!", x, "\n")
foo_.baz <- function(x) cat("Baz!", x, "\n")
Run Code Online (Sandbox Code Playgroud)
现在测试一下:
a <- structure(1:5, class="bar")
b <- structure(6:10, class="baz")
foo(a)
## Foo! 10 20 30 40 50
foo(b)
## Baz! 60 70 80 90 100
Run Code Online (Sandbox Code Playgroud)
有关广泛使用的包中的示例,请参阅dplyr :: mutate的源代码
2)NextMethod另一种方法是给每一个对象两个类的与类载体"foo"
制成的子类"bar"
中的情况下a
和"baz"
在的情况下b
.然后用NextMethod
.解决方案(1)似乎简单,它可能看起来奇怪的是"foo"
是两者的子类"bar"
和"baz"
但这里是这一个以防万一的例子:
foo <- function(x) UseMethod("foo")
foo.foo <- function(x) {
x <- x * 10
NextMethod()
}
foo.bar <- function(x) cat("Foo!", x, "\n")
foo.baz <- function(x) cat("Baz!", x, "\n")
Run Code Online (Sandbox Code Playgroud)
测试指出的是,我们已经改变了的定义a
,并b
让他们用这种方式工作:
a <- structure(1:5, class= c("foo", "bar"))
b <- structure(6:10, class = c("foo", "baz"))
foo(a)
## Foo! 10 20 30 40 50
foo(b)
## Baz! 60 70 80 90 100
Run Code Online (Sandbox Code Playgroud)