我用自己的构造函数创建了三个S4类。 A类继承自data.frame,并有一个名为“color”的附加插槽。 B类继承自A,只向继承的数据帧添加一个变量。 C类继承自B,并且还将继承的数据框扩展为一个变量。这是一个例子:
prototype
但是,我必须做错事,因为validObject(.A())和validObject(.B())都返回TRUE而validObject(.C())失败
.A <- setClass("A",
representation(color = "character"),
prototype(color = NA_character_),
contains = "data.frame",
validity = function(object) {
errors <- character()
if (length(object@color) != 1) {
msg <- paste("color must be of length = 1")
errors <- c(errors, msg)
}
if (length(errors) == 0) TRUE else errors
}
)
A <- function(x = NA_real_,
y = NA_real_,
color = NA_character_, ...) {
data <- data.frame("x" = x, "y" = y, ...)
.A(data, color = color)
}
.B <- setClass("B",
contains = "A")
B <- function(x = NA_real_,
y = NA_real_,
z = NA_real_,
color = NA_character_, ...) {
.B(A(x = x, y = y, z = z, color = color, ...))
}
.C <- setClass("C",
contains = "B")
C <- function(x = NA_real_,
y = NA_real_,
z = NA_real_,
w = NA_real_,
color = NA_character_, ...) {
.C(B(x = x, y = y, z = z, w = w, color = color, ...))
}
如果我从A类的表示中删除了有效性约束,那么validObject(.C())将返回TRUE。
我做错了什么?
感谢阅读!