2012-06-07 32 views
22

我需要一些专业术语以及一小段示例代码。不同类型的对象具有输入对象名称的特定方式,并按下Enter键,lm对象显示模型摘要,矢量列出矢量内容。需要的示例:更改对象的默认打印方法

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

我该怎么做呢?

+1

也许看到'?方法' - 在页面底部附近有例子。 – BenBarnes

+1

如果试图改变一个包含NAMESPACE的包所提供的S3类对象的打印方法,这是一个现代版本的R的所有包,那么请小心。如果为现有的一个新的'print()类,您可能需要'assignInNamespace(....)'您的本地版本的打印方法。 –

+0

感谢您的指导本和提示加文。 –

回答

25

下面是一个让你开始的例子。一旦您了解了如何分派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 
+0

正是我需要的。我的语言是错误的“type”=“class”,“输出方式”=“方法” –

+0

mm的目的是告诉我该对象不必是类“myMatrix”的打印功能工作? –

+0

是的。我基本上将它包含在内,以帮助揭开整个主题的神秘面纱,并且证明'print.myMatrix'只是另一个可以应用于任何对象的函数。唯一特别的是它的名字的'.myMatrix'部分,它允许在对'print()'的调用进行评估时调用'UseMethod'调用来找到它。不知道它有多成功,但那是我的意图。 –

相关问题