我定义了一些S4矩阵,它的类是lazyMatrix。如果M是这样一个矩阵,我想将M[2, ]定义为M的第二行,而M[2]定义为M的第二个系数(当枚举系数一列又一列时)。
因此,我定义了这两个S4方法:
setMethod( # to extract a coefficient
"[",
signature("lazyMatrix", i = "numeric"),
function(x, i) {
......
}
)
setMethod( # to extract a row
"[",
signature("lazyMatrix", i = "numeric", j = "missing", drop = "ANY"),
function(x, i, j, drop) {
......
}
)但是M[2, ]和M[2]都返回M的第二行。我试图交换两个方法定义的顺序,这不会改变任何事情。
发布于 2022-11-12 18:13:09
我在洋葱包的源代码中找到了一个解决方案:
setMethod(
"[",
signature("lazyMatrix", i = "numeric", j = "missing", drop = "missing"),
function(x, i, j, ..., drop) {
n_args <- nargs()
if(n_args == 3L) { # M[i, ]
......
} else if(n_args == 2L) { # M[i]
......
} else {
stop("Invalid arguments in subsetting.")
}
}
)
setMethod(
"[",
signature("lazyMatrix", i = "numeric", j = "missing", drop = "ANY"),
function(x, i, j, ..., drop) {
n_args <- nargs()
if(n_args == 4L) { # M[i, ]
......
} else if(n_args == 3L) { # M[i]
......
} else {
stop("Invalid arguments in subsetting.")
}
}
)在找到此解决方案之前,我尝试在尝试中使用nargs(),但没有成功。诀窍是添加...参数。但我不明白这是怎么回事。如果你能解释的话,请留下另一个答案或评论。
https://stackoverflow.com/questions/74415282
复制相似问题