3
> foo <- structure(list(one=1,two=2), class = "foo")

> cat(foo)
Error in cat(list(...), file, sep, fill, labels, append) : 
  argument 1 (type 'list') cannot be handled by 'cat'

OK、これをジェネリック cat に追加します。

> cat.foo<-function(x){cat(foo$one,foo$two)}
> cat(foo)
Error in cat(list(...), file, sep, fill, labels, append) : 
  argument 1 (type 'list') cannot be handled by 'cat'

サイコロはありません。

4

2 に答える 2

4

できません。 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"

これは、2 番目以降のすべての引数のクラスが無視されることを意味します。

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
于 2014-02-19T20:02:07.517 に答える