27

我需要一些行话方面的帮助,以及一小段示例代码。不同类型的对象在输入对象名称并回车时都有特定的输出方式,lm 对象显示模型的摘要,vector 列出向量的内容。

我希望能够编写自己的方式来“显示”特定类型对象的内容。理想情况下,我希望能够将其与现有类型的对象分开。

我该怎么做呢?

4

1 回答 1

31

这是一个让您入门的示例。一旦您了解了如何分派 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 
于 2012-06-07T19:26:58.447 回答