D.8 泛型

I’d like to prefix all these solutions with ‘Here’s how to do it, but don’t actually do it you crazy fool’. It’s on a par with redefining pi, or redefining ‘+’. And then redefining ‘<-’. These techniques have their proper place, and that would be in the currently non-existent obfuscated R contest. No, the R-ish (iRish?) way is to index vectors from 1. That’s what the R gods intended!

— Barry Rowlingson 53

如果要让下标从 0 开始的话,我们需要在现有的向量类型 vector 上定义新的向量类型 vector0,在其上并且实现索引运算 [ 和赋值修改元素的运算 [<-

# https://stat.ethz.ch/pipermail/r-help/2004-March/048682.html
as.vector0 <- function(x) structure(x, class = "vector0") # 创建一种新的数据结构 vector0
as.vector.vector0 <- function(x) unclass(x)
"[.vector0" <- function(x, i) as.vector0(as.vector.vector0(x)[i + 1]) # 索引操作
"[<-.vector0" <- function(x, i, value) { # 赋值操作
  x <- as.vector.vector0(x)
  x[i + 1] <- value
  as.vector0(x)
}
print.vector0 <- function(x) print(as.vector.vector0(x)) # 实现 print 方法

举个例子看看

1:10 # 是一个内置的现有向量类型 vector
##  [1]  1  2  3  4  5  6  7  8  9 10
x <- as.vector0(1:10) # 转化为新建的 vector0 类型
x[0:4] <- 100 * x[0:4] # 对 x 的元素替换修改
x
##  [1] 100 200 300 400 500   6   7   8   9  10

第三方 R 包大大扩展了 Base R 函数 plot() 的功能,比如 mgcvnlme 包和 lattice 包等,表 D.1 列出当前环境下, plot() 绘图方法。

## Warning in matrix(methods("plot"), ncol = 3): data length [52] is not a sub-
## multiple or multiple of the number of rows [18]
表 D.1: 泛型函数
A B C
plot.acf plot.intervals.lmList plot.ranef.lme
plot.ACF plot.isoreg plot.ranef.lmList
plot.augPred plot.jam plot.raster
plot.compareFits plot.lm plot.shingle
plot.data.frame plot.lme plot.simulate.lme
plot.decomposed.ts plot.lmList plot.spec
plot.default plot.medpolish plot.spline
plot.dendrogram plot.mlm plot.stepfun
plot.density plot.nffGroupedData plot.stl
plot.ecdf plot.nfnGroupedData plot.table
plot.factor plot.nls plot.trellis
plot.formula plot.nmGroupedData plot.ts
plot.function plot.pdMat plot.tskernel
plot.gam plot.ppr plot.TukeyHSD
plot.gls plot.prcomp plot.Variogram
plot.hclust plot.princomp plot.xyVector
plot.histogram plot.profile.nls plot.acf
plot.HoltWinters plot.R6 plot.ACF