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

user1854786 picture user1854786 · Nov 26, 2012 · Viewed 31.5k times · Source

I have a matrix I am trying to transpose in R but the t() function does not return the right answer. How can I transpose the matrix?

> xx=matrix(c(3,7,4,8),2,byrow=TRUE)
> xx
     [,1]  [,2]
[1,]    3     7
[2,]    4     8
> t(xx)
[1] 0.7071068 0.7071068

Answer

Josh O'Brien picture Josh O'Brien · Nov 26, 2012

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