我想为我的类(class)实现一个插入方法 myClass
对于内部通用 [<-
(~ help(Extract)
)。
在将实际插入传递给 [<-
之前,该方法应该运行一堆测试。通过 NextMethod()
.
我明白那个:
NextMethod()
call 通常不需要任何参数(尽管手动提供它们似乎也无济于事)。 这是我的代表:
x <- c(1,2)
class(x) <- c("myClass", "numeric")
`[<-.myClass` <- function(x, i, j, value, foo = TRUE, ...) {
if (foo) {
stop("'foo' must be false!")
}
NextMethod()
}
x[1] <- 3 # this errors out with *expected* error message, so dispatch works
x[1, foo = FALSE] <- 3 # this fails with "incorrect number of subscripts
似乎正在发生的是
NextMethod()
也通过foo
到内部通用 [<-
, 哪个错误 foo
对于另一个索引,因此会出错(因为在这种情况下,x
没有第二个维度来索引)。我还尝试明确提供参数 no
NextMethod()
, 但这也失败了(请参阅 break 下面的 reprex )。我怎样才能避免哽咽
NextMethod()
对我的方法有额外的参数吗? (奖励:有人知道为内部泛型构建方法的好资源吗?@Hadleys adv-r 在这件事上有点短)。
带有显式参数的表示:
x <- c(1,2)
class(x) <- c("myClass", "numeric")
`[<-.myClass` <- function(x, i = NULL, j = NULL, value, foo = TRUE, ...) {
if (foo) {
stop("'foo' must be false!")
}
NextMethod(generic = "`[<-`", object = x, i = i, j = j, value = value, ...)
}
x[1] <- 3 # this errors out with expected error message, so dispatch works
x[1, foo = FALSE] <- 3 # this fails with "incorrect number of subscripts
最佳答案
除了剥离类(class)(复制 x
)之外,我没有看到解决此问题的简单方法
`[<-.myClass` <- function(x, i, value, ..., foo = TRUE) {
if (foo) {
cat("hi!")
x
} else {
class_x <- class(x)
x <- unclass(x)
x[i] <- value
class(x) <- class_x
x
}
}
x <- structure(1:2, class = "myClass")
x[1] <- 3
#> hi!
x[1, foo = FALSE] <- 3
x
#> [1] 3 2
#> attr(,"class")
#> [1] "myClass"
这不是一个通用的方法 - 它只需要
[
, [<-
等,因为它们不使用常规规则进行参数匹配:Note that these operations do not match their index arguments in the standard way: argument names are ignored and positional matching only is used. So
m[j = 2, i = 1]
is equivalent tom[2, 1]
and not tom[1, 2]
.
(来自
?`[`
中的“参数匹配”部分)这意味着您的
x[1, foo = FALSE]
相当于x[1, FALSE]
然后您会收到一条错误消息,因为 x
不是矩阵。不起作用的方法:
NextMethod()
提供附加参数:这只能增加参数的数量,不能减少它foo
与 rm(foo)
: 这会导致关于 undefined foo
的错误. foo
缺少符号:这会导致错误 foo
不提供没有默认参数。 关于r - 如何为内部泛型的方法添加额外的参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51873138/