可以在 R 中重载函数?如 plot
函数,即两个函数名称相同但参数列表不同,如何实现?
谢谢!!!
最佳答案
听起来您正在寻找的是 methods
.许多常用函数( print
、 summary
、 plot
)在 R 中重载,根据 class
应用不同的方法它们被应用到的对象。
您提到了 plot
,但我发现从 print
开始更容易. R 中使用的一种常见数据结构是 class
的对象。的 data.frame
.如果你看 methods("print")
,您将找到具有此类的对象的特定打印方法。这使其打印与正常 list
不同虽然 data.frame
, 是 list
的特殊类型在 R。
例子:
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
是可能的。自己做计算。虽然这看起来很方便,但最终也会导致代码的“透明”程度降低。
关于r - R中有函数重载吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20812208/