cat(foo) Error in cat(list(...), file, sep, fill, labels, appe...">

How to send cat to R S3?

> 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 I will add this to the birth 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'

No dice.

+3
source share
2 answers

You can not. cat()is not a common function, so you cannot write methods for it.

You can create a new version cat()that is generic:

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)
}

But the dispatching semantics are ...not defined (I could not find where, if anywhere, it is documented). It seems that sending only occurs on the first element in ...:

cat.integer <- function(...) "int"
cat.character <- function(...) "chr"
cat(1L)
#> [1] "int"
cat("a")
#> [1] "chr"

This means that the class of the second and subsequent arguments is ignored:

cat(1L, "a")
#> [1] "int"
cat("a", 1L)
#> [1] "chr"

If you want to add a method footo cat(), you just need an additional check:

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
+3
source

- , , - , cat list -:

cat <- function(...) do.call(base::cat, as.list(do.call(c, list(...))))

R> cat(list(1,2))
1 2R> cat(list(1,2), sep=',')
1,2R> cat(c(1,2))
1 2R> cat(c(1,2), sep=',')
1,2R> 
+2

All Articles