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

R 所需示例:更改对象的默认打印方法,r,R,我需要一些行话方面的帮助,以及一小段示例代码。不同类型的对象有一种特定的输出方式当您键入对象名称并按enter键时,lm对象显示模型摘要,向量列出向量的内容 我希望能够以自己的方式“显示”特定类型对象的内容。理想情况下,我希望能够将其与现有类型的对象分开 我该怎么做呢?下面是一个让您开始学习的示例。一旦您了解了S3方法是如何调度的,请查看方法(“print”)返回的任何打印方法,以了解如何实现更有趣的打印样式 ## Define a print method that will be autom

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

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


我该怎么做呢?

下面是一个让您开始学习的示例。一旦您了解了S3方法是如何调度的,请查看
方法(“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 
##定义一个打印方法,该方法将在打印()时自动调度
##对类“myMatrix”的对象调用

print.myMatrix可能会看到
?方法
-在页面底部附近有一些示例。如果您试图更改S3类对象的打印方法,该对象是由具有命名空间的包提供的,这些包都是具有现代版本R的包。如果您为现有类编写新的
print()
方法,您可能需要
assignInNamespace(..)
print方法的本地版本。感谢Ben的指导和tip Gavin。这正是我需要的。我的语言完全错了“类型”=“类”,“输出方式”=“方法”mm的目的是向我展示打印功能不必使用“myMatrix”类的对象?是的。我加入它基本上是为了帮助揭开整个主题的神秘面纱,并表明
print.myMatrix
只是可以应用于任何对象的另一个函数。它唯一的特殊之处是它名称的
.myMatrix
部分,它允许在计算对
print()
的调用时调用的
UseMethod
调用找到它。不知道它有多成功,但这是我的意图。我把
j[I,]
改为
x[I,]
,因为它抛出了错误。我很想改变:
class(m)