我想编写一个处理多种数据类型的函数.下面是一个有效的例子,但看起来很笨重.这样做有标准(或更好)的方法吗?
(这是像这样的时候我想念Matlab,其中一切都是一种类型:>)
myfunc = function(x) {
# does some stuff to x and returns a value
# at some point the function will need to find out the number of elements
# at some point the function will need to access an element of x.
#
# args:
# x: a column of data taking on many possible types
# e.g., vector, matrix, data.frame, timeSeries, list
x.vec <- as.vector(as.matrix(as.data.frame(x)))
n <- length(x.vec)
ret <- x.vec[n/3] # this line only for concreteness
return(ret)
}
Run Code Online (Sandbox Code Playgroud)
使用S3方法.一个让你入门的简单例子:
myfunc <- function(x) {
UseMethod("myfunc",x)
}
myfunc.data.frame <- function(x) {
x.vec <- as.vector(as.matrix(x))
myfunc(x.vec)
}
myfunc.numeric <- function(x) {
n <- length(x)
ret <- x[n/3]
return(ret)
}
myfunc.default <- function(x) {
stop("myfunc not defined for class",class(x),"\n")
}
Run Code Online (Sandbox Code Playgroud)
两个笔记:
...语法传递给功能的任何额外参数.如果你正在扩展现有的S3方法(例如编写像summary.myobject这样的东西),那么包含它...是一个好主意,因为你可以传递给传统规范函数的常规参数.print.myclass <- function(x,...) {
print(x$keyData,...)
}