听起来您正在寻找的是methods。许多常用函数(print、summary、plot)在 R 中被重载,根据它们所应用的对象的 class 应用不同的方法。
您提到了plot,但我发现从print 开始更容易。 R 中使用的一种常见数据结构是class 的对象data.frame。如果您查看methods("print"),您会发现该类的对象的特定打印方法。这使它与普通的list 打印不同,尽管data.frame 是R 中list 的一种特殊类型。
例子:
mydf <- data.frame(lengths = 1:3, values = 1:3, blah = 1:3)
mydf ### SAME AS print(mydf)
# lengths values blah
# 1 1 1 1
# 2 2 2 2
# 3 3 3 3
print.default(mydf) ## Override automatically calling `print.data.frame`
# $lengths
# [1] 1 2 3
#
# $values
# [1] 1 2 3
#
# $blah
# [1] 1 2 3
#
# attr(,"class")
# [1] "data.frame"
print(unclass(mydf)) ## Similar to the above
# $lengths
# [1] 1 2 3
#
# $values
# [1] 1 2 3
#
# $blah
# [1] 1 2 3
#
# attr(,"row.names")
# [1] 1 2 3
当然,您也可以创建自己的methods。当您要打印具有特殊格式的内容时,这可能很有用。这是一个打印带有一些不必要垃圾的向量的简单示例。
## Define the print method
print.SOexample1 <- function(x, ...) {
cat("Your values:\n============",
format(x, width = 6), sep = "\n>>> : ")
invisible(x)
}
## Assign the method to your object
## "print" as you normally would
A <- 1:5
class(A) <- "SOexample1"
print.SOexample1(A)
# Your values:
# ============
# >>> : 1
# >>> : 2
# >>> : 3
# >>> : 4
# >>> : 5
## Remove the "class" value to get back to where you started
print(unclass(A))
# [1] 1 2 3 4 5
您可以想象,可以让您的methods 自己进行计算。虽然这看起来很方便,但最终也会导致代码不那么“透明”。