你不能。 cat()
不是通用函数,因此您不能为其编写方法。
您可以使新版本cat()
具有通用性:
cat <- function(..., file = "", sep = " ", fill = FALSE, labels = NULL,
append = FALSE) {
UseMethod("cat")
}
cat.default <- function(..., file = "", sep = " ", fill = FALSE, labels = NULL,
append = FALSE) {
base::cat(..., file = file, sep = sep, fill = fill, labels = labels,
append = append)
}
但是调度的语义...
没有很好的定义(我找不到它在哪里,如果在任何地方,它被记录在案)。看起来调度仅基于中的第一个元素发生...
:
cat.integer <- function(...) "int"
cat.character <- function(...) "chr"
cat(1L)
#> [1] "int"
cat("a")
#> [1] "chr"
这意味着忽略第二个和所有后续参数的类:
cat(1L, "a")
#> [1] "int"
cat("a", 1L)
#> [1] "chr"
如果你想添加一个foo
方法cat()
,你只需要一些额外的检查:
cat.foo <- function(..., file = "", sep = " ", fill = FALSE, labels = NULL,
append = FALSE) {
dots <- list(...)
if (length(dots) > 1) {
stop("Can only cat one foo at a time")
}
foo <- dots[[1]]
cat(foo$one, foo$two, file = file, sep = sep, fill = fill, labels = labels,
append = append)
cat("\n")
}
foo <- structure(list(one=1,two=2), class = "foo")
cat(foo)
#> 1 2