专注系列化、高质量的R语言教程
推文索引 | 联系小编 | 付费合集
本篇推文缘起于上篇推文plot3D | 三维数据绘图(3):mesh函数、surf3D函数、spheresurf3D函数。学堂君在介绍surf3D()
函数时举了两个例子。
第一个例子是绘制球形:
library(plot3D)
M = mesh(
x = seq(0, 2*pi, length.out = 100),
y = seq(0, pi, length.out = 100)
)
phi = M$x
theta = M$y
r = 2
x = r*sin(theta)*cos(phi)
y = r*sin(theta)*sin(phi)
z = r*cos(theta)
surf3D(x,y,z, colvar = z)

第二个例子是在第一个例子的基础上变化了r
。其中x
、y
、z
、surf3D(x,y,z)
部分的代码虽然不变,但它们都与r
有关,并且不会跟随r
自动变化,因此需要重复书写这段代码:
r0 = seq(0, 2, length.out = 100)
r = matrix(rep(r0, 100), nrow = 100, byrow = T)
x = r*sin(theta)*cos(phi)
y = r*sin(theta)*sin(phi)
z = r*cos(theta)
surf3D(x,y,z)

这就让学堂君想到了面向对象编程范式(OOP)的优点了。目前关于OOP,学堂上有三篇专门的推文,介绍了两个工具包:
R语言与面向对象的编程(1):proto对象
R语言与面向对象的编程(2):proto对象(续)
R语言与面向对象的编程(3):R6类
先看proto
工具包:
首先创建一个proto对象plotfun
:
library(plot3D)
library(proto)
plotfun <- proto(
M = mesh(
x = seq(0, 2*pi, length.out = 100),
y = seq(0, pi, length.out = 100)
),
plot = function(., r) {
phi = M$x
theta = M$y
x = r*sin(theta)*cos(phi)
y = r*sin(theta)*sin(phi)
z = r*cos(theta)
surf3D(x,y,z, colvar = z)
}
)
实现第一个例子:
plotfun$plot(r = 2)

实现第二个例子:
r0 = seq(0, 2, length.out = 100)
r = matrix(rep(r0, 100), nrow = 100, byrow = T)
plotfun$plot(r = r)

再看R6
工具包:
首先定义类plotfun2
: