如果您在矩阵上调用rep
,它会重复其元素而不是整个矩阵。传统的修复方法是调用 rep(list(theMatrix),...)
。我想扩展 rep
以便它自动执行此操作。
我尝试使用
rep.matrix<-function(x,...) rep(list(x),...)
确实将 rep.matrix
添加到 methods(rep)
> methods(rep)
[1] rep.bibentry* rep.Date rep.factor rep.matrix
[5] rep.numeric_version rep.POSIXct rep.POSIXlt rep.roman*
see '?methods' for accessing help and source code
但是,在矩阵上调用rep似乎并未分派(dispatch)到rep.matrix
。
> rep(diag(5),3)
[1] 1 0 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0 1 1 0 0 0 0 0 1 0 0 0 0 0 1 0 0 0
[42] 0 0 1 0 0 0 0 0 1 1 0 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0 1
尽管直接调用 rep.matrix
没有错误。
> rep.matrix(diag(5),3)
[[1]]
[,1] [,2] [,3] [,4] [,5]
[1,] 1 0 0 0 0
[2,] 0 1 0 0 0
[3,] 0 0 1 0 0
[4,] 0 0 0 1 0
[5,] 0 0 0 0 1
[[2]]
[,1] [,2] [,3] [,4] [,5]
[1,] 1 0 0 0 0
[2,] 0 1 0 0 0
[3,] 0 0 1 0 0
[4,] 0 0 0 1 0
[5,] 0 0 0 0 1
[[3]]
[,1] [,2] [,3] [,4] [,5]
[1,] 1 0 0 0 0
[2,] 0 1 0 0 0
[3,] 0 0 1 0 0
[4,] 0 0 0 1 0
[5,] 0 0 0 0 1
如果我创建并使用 rep.array
而不是 rep.matrix
,我会得到相同的结果。
我的错误在哪里?为什么 rep
不分派(dispatch)到 rep.matrix
?我是否使用了错误的对象系统?
最佳答案
这是不可能的。 The documentation is not too forthcoming about this fact ,但 rep
是一个内部通用函数,如 here 所解释的那样。这意味着它只会分派(dispatch)到 is.object
返回 TRUE
的事物。矩阵不是这样的东西,因此您不能将 rep
扩展到矩阵并将其分派(dispatch)给它们。
关于r - 将代表扩展到矩阵?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66284726/