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

Bra*_*sen 25 r

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

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

我该怎么做呢?

Jos*_*ien 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 
Run Code Online (Sandbox Code Playgroud)

  • 我将`j [i,]`更改为`x [i,]`,因为它抛出了错误.我很想改变:`class(m)< - "myMatrix"`到`class(m)< - c("myMatrix",class(m))`这样你的新类就可以继承"矩阵"方法,但我决定只建议你这样做. (2认同)