扩展代表矩阵? [英] Extending rep to matrices?

查看:59
本文介绍了扩展代表矩阵?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果在矩阵上调用 rep ,它将重复其元素而不是整个矩阵.传统的解决方法是调用 rep(list(theMatrix),...).我想扩展 rep 以便它自动执行此操作.

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.

我尝试使用

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似乎没有调度到 rep.matrix .

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

尽管直接调用 rep.matrix 可以正常工作.

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

如果我创建并使用 rep.array 而不是 rep.matrix ,则会得到相同的结果.

I get the same outcomes if I create and use rep.array instead of rep.matrix.

我的错误在哪里?为什么 rep 不调度到 rep.matrix ?我是否以某种方式使用了错误的对象系统?

Where is my error? Why isn't rep dispatching to rep.matrix? Did I use the wrong object system somehow?

推荐答案

此操作无法完成.有关此事实的文档并不太有用,但是 rep 内部泛型函数,如此处.这意味着它将仅分派给 is.object 返回 TRUE 的事物.矩阵不是这样的事情,因此您不能将 rep 扩展到矩阵并将其分派给它们.

This cannot be done. The documentation is not too forthcoming about this fact, but rep is an internal generic function, as explained here. This means that it will only dispatch to things where is.object returns TRUE. Matrices are not such a thing, so you cannot extend rep to matrices and have it dispatch to them.

这篇关于扩展代表矩阵?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆