听起来你正在寻找的是什么methods.许多常用功能(print,summary,plot)过载中的R具有取决于被施加不同的方法class他们被应用到对象的.
你提到过plot,但我发现从开始看起来更容易print.是R中使用的一个通用的数据结构是的目的class的data.frame.如果您查看methods("print"),您将找到具有此类的对象的特定打印方法.这使得它的打印方式与普通打印不同,list尽管a data.frame,是listR中的一种特殊类型.
例:
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
Run Code Online (Sandbox Code Playgroud)
当然,您也可以创建自己的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
Run Code Online (Sandbox Code Playgroud)
可以想象,您可以自己methods进行计算.虽然这看起来很方便,但最终也会导致代码不那么"透明".