If you call rep
on a matrix, it repeats its elements rather than the entire matrix. The traditional fix is to call rep(list(theMatrix),...)
. I want to extend rep
so that it does this automatically.
I attempted to use
rep.matrix<-function(x,...) rep(list(x),...)
which did indeed add rep.matrix
to 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
However, calling rep on a matrix did not appear to dispatch to 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
Although direct calls to rep.matrix
worked without error.
> 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
I get the same outcomes if I create and use rep.array
instead of rep.matrix
.
Where is my error? Why isn't rep
dispatching to rep.matrix
? Did I use the wrong object system somehow?