我在我的包内部使用 {patchwork} 包。我想利用拼凑算术运算符(即 |
、\
等)。
我为我的对象类导出方法。例如:
"|.ggsurvfit" <- function(e1, e2) {
build_and_wrap(e1) | build_and_wrap(e2)
}
在上面的示例中,当传递“ggsurvfit”类的图形时,它会被处理并转换为“ggplot”类,然后使用拼凑方法“|.ggplot”
执行。
我遇到的问题是用户需要将典型的 ggplot 与 ggsurvfit 图结合起来。例如p1 | p2
其中 p1 具有“ggplot”类,而 p2
具有“ggsurvfit”类。 patchwork 包导出一个正在使用的 |.ggplot
方法。但我们收到错误,因为 |.ggplot
不知道如何执行第二个参数(即“ggsurvfit”类)所需的处理。
我正在尝试编写一个 S3 方法 |.ggplot
来正确处理第二个参数。但我什么也做不了……呃!
有没有办法通过指定的 S3 方法强制执行某些代码,即如何使用 patchwork 的 |.ggplot
方法强制执行?
"|.ggplot" <- function(e1, e2) {
e2 <- build_and_wrap(e2) # process the second argument
# patch together the figures using the patwork `|.ggplot` method
withr::with_namespace(
package = "patchwork",
code = e1 | e2
)
}
最佳答案
S3 不适用于多重调度。 S4是。一个原则性的方法是将 ggsurvfit 定义为 ggplot 的 S4 子类,然后为 |
(或任何其他内部通用的)定义合适的 S4 方法。二元运算符)。
setOldClass("ggplot")
setClass("ggsurvfit", contains = "ggplot", slots = c(p = "ggplot"))
setMethod("|", c("ggplot", "ggsurvfit"),
function(e1, e2) <do stuff with e1 and e2@p here>)
setMethod("|", c("ggsurvfit", "ggplot"),
function(e1, e2) <do stuff with e1@p and e2 here>)
setMethod("|", c("ggsurvfit", "ggsurvfit"),
function(e1, e2) <do stuff with e1@p and e2@p here>)
您的包的 DESCRIPTION
和 NAMESPACE
文件需要相应更改。
我们可以用一个简单的例子来测试它是否有效。这里,类 a
和 b
取代了类 ggplot
和 ggsurvfit
,以及 S3 方法 |.a
取代 patchwork 中的 |.ggplot
:
setOldClass("a")
setClass("b", contains = "a", slots = c(p = "a"))
.S3method("|", "a", function(e1, e2) "aa")
setMethod("|", c("a", "b"), function(e1, e2) "ab")
setMethod("|", c("b", "a"), function(e1, e2) "ba")
setMethod("|", c("b", "b"), function(e1, e2) "bb")
a <- structure(1, class = "a")
b <- new("b", p = structure(2, class = "a"))
a | a
## [1] "aa"
a | b
## [1] "ab"
b | a
## [1] "ba"
b | b
## [1] "bb"
有关 S3 和 S4 混合使用的更多详细信息,您可以查看 ?Methods_for_S3
、?setOldClass
和 ?S3Part
.
关于r - 强制执行指定的S3方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74072102/