how to transpose a matrix in r if the usual `t( )` doesn't work?

你离开我真会死。 提交于 2019-12-04 05:10:06
Josh O'Brien

This answer is incorrect, but in ways that were enlightening to me and might be to others, so I'll leave it up.

As @mnel noted, the base R function t() must be masked by another function of the same name. Try removing the function t() and doing t(xx) again. I guarantee you'll get the correct results.

What do you get when you run this:

rm(t)
t(xx)

If (despite my guarantee!) it still doesn't work, you can fully specify the version of t() you want to use, like this:

base::t(xx)

Here's why the two suggestions above are insufficient

From ?UseMethod:

Namespaces can register methods for generic functions. To support this, ‘UseMethod’ and ‘NextMethod’ search for methods in two places: first in the environment in which the generic function is called, and then in the registration data base for the environment in which the generic is defined (typically a namespace). So methods for a generic function need to be available in the environment of the call to the generic, or they must be registered. (It does not matter whether they are visible in the environment in which the generic is defined.)

I wrongly assumed that S3 method dispatch looks for methods like t.default() first in base:::.__S3MethodsTable__. and then perhaps in asNamespace("base")before looking in the calling environment, whereas the reverse is closer to the truth.


Edit from GSee

Here's an interactive session to demonstrate what could have been the problem.

> t <- function(x, ...) print("generic masked")
> t.default <- function(x, ...) print("t.default masked")
> t.matrix <- function(x, ...) print("t.matrix was used")
> t.numeric <- function(x, ...) print("t.numeric was used")
> xx=matrix(c(3,7,4,8),2,byrow=TRUE)
> t(xx)
[1] "generic masked"
> base::t(xx)
[1] "t.matrix was used"
> rm(t.matrix)
> base::t(xx)
[1] "t.numeric was used"
> rm(t.numeric)
> base::t(xx)
[1] "t.default masked"
> rm(t.default)
> base::t(xx)
     [,1] [,2]
[1,]    3    4
[2,]    7    8
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!