假设我想写一个函数R
这是对某些数据进行充分统计的函数。例如,假设函数,调用它foo.func
仅取决于数据样本的样本均值。为了方便起见,我认为用户可能喜欢传递到foo.func
随机变量的样本(在这种情况下foo.func
计算样本平均值),or样本均值本身,这就是全部foo.func
需要。出于效率的考虑,如果有多个功能,例如foo.func
被调用可以取样本平均值。在这种情况下,平均值只需要计算一次(在我遇到的实际问题中,所讨论的样本统计数据可能需要大量计算)。
总而言之,我想写foo.func
初学者(传递数据,让函数计算足够的统计数据)和专家(预先计算足够的统计数据以提高效率并将其传递)都可以访问。为此有哪些推荐做法?我是否传入了逻辑标志?多个参数?一些方法可能是:
#optional arguments
foo.func <- function(xdata, suff.stats=NULL) {
if (is.null(suff.stats)) {
suff.stats <- compute.suff.stats(x)
}
#now operate on suff.stats
}
or
#flag input
foo.func <- function(data.or.stat, gave.data=TRUE) {
if (gave.data) {
data.or.stat <- compute.suff.stats(data.or.stat)
}
#now operate on data.or.stat
}
我认为我倾向于前者
R 实现多态性的方法是通过 CLOS(Common Lisp 的 OO)模型,其中方法与通用函数(动词)而不是类(名词)相关联。例如,
# suprising that there is not an equivalent function in R
# to propagate inheritance...
addclass <- function(x,classname) structure(x,class=append(class(x),classname))
# this should be your main function that does stuff
# here, the identity function is assigned for example
dostuff <- identity
# define generic function and methods
foo <- function(x,...) UseMethod("foo")
foo.raw <- function(x,...) dostuff(mean(x))
foo.stats <- function(x,...) dostuff(x)
# define two types of inputs
x <- 1:10
x <- addclass(x,"raw")
y <- 5
y <- addclass(y,"stats")
# apply
foo(x)
# [1] 5.5
foo(y)
# [1] 5
# attr(,"class")
# [1] "numeric" "stats"
该示例使用 RS3
OOP模型,我认为已经足够了;S4
更现代、更安全,但增加了很多样板。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)