需要的示例:更改对象的默认打印方法

时间:2012-06-07 19:16:48

标签: r

我需要一些行话的帮助,以及一小段示例代码。当您键入对象的名称并按Enter键时,不同类型的对象具有输出自身的特定方式,lm对象显示模型的摘要,向量列出向量的内容。

我希望能够用自己的方式来“显示”特定类型对象的内容。理想情况下,我希望能够从现有类型的对象中分离出来。

我将如何做到这一点?

1 个答案:

答案 0 :(得分:28)

这是一个让你入门的例子。一旦掌握了如何调度S3方法的基本概念,请查看methods("print")返回的任何打印方法,看看如何实现更有趣的打印样式。

## Define a print method that will be automatically dispatched when print()
## is called on an object of class "myMatrix"
print.myMatrix <- function(x) {
    n <- nrow(x)
    for(i in seq_len(n)) {
        cat(paste("This is row", i, "\t: " ))
        cat(x[i,], "\n")
        }
}

## Make a couple of example matrices
m <- mm <- matrix(1:16, ncol=4)

## Create an object of class "myMatrix". 
class(m) <- c("myMatrix", class(m))
## When typed at the command-line, the 'print' part of the read-eval-print loop
## will look at the object's class, and say "hey, I've got a method for you!"
m
# This is row 1   : 1 5 9 13 
# This is row 2   : 2 6 10 14 
# This is row 3   : 3 7 11 15 
# This is row 4   : 4 8 12 16 

## Alternatively, you can specify the print method yourself.
print.myMatrix(mm)
# This is row 1   : 1 5 9 13 
# This is row 2   : 2 6 10 14 
# This is row 3   : 3 7 11 15 
# This is row 4   : 4 8 12 16