gpt4 book ai didi

r - 需要的示例 : Change the default print method of an object

转载 作者:行者123 更新时间:2023-12-03 10:41:37 25 4
gpt4 key购买 nike

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

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

我该怎么做呢?

最佳答案

这是一个让您入门的示例。一旦您了解了 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

关于r - 需要的示例 : Change the default print method of an object,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10938427/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com