what is the differnces? and when to use each?
Gabor Grothendieck
2004-Sep-04 12:46 UTC
[R] what is th diffence among "cat","print"and"format"
ronggui wong <0034058 <at> fudan.edu.cn> writes:> what is the differnces? > and when to use each?I think the main difference is that cat does not know about objects. It just unclasses the input (someone can correct me on this if this is not true), converts each of the unclassed inputs to character and concatenates and displays the contatenated result on the standard output or to a file, if specified. For example, x <- 3 class(x) <- "myclass" cat(x, "\n") cat(unclass(x), "\n") # same In contrast, print, format and as.character are S3 generics which look at the class of their first argument and dispatch a different method depending on which class is. e.g. # using x from above print.myclass <- function(x) cat("***", x, "***\n") print(x) The dispatched method will understand how to represent the object as a character string so that it can display it in the case of print or return it as a character string in the case of format and as.character. as.character is often just a wrapper around format, e.g. the source for as.character.Date is: as.character.Date <- function(x, ...) format(x, ...) You can find out which methods are actually available using: methods(print) methods(format) methods(as.character) The default method is used, e.g. print.default, if there is no available method for the class of the object. If one wants to display a character string with control over newlines then one typically uses cat. If one wants to display an object one uses print or else converts it to a character string using format or as.character and then display it using cat. If you just type the name of an object into R then it invokes the print method for that object. e.g. x # same as print(x)