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

2

7

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
Asceticism answered 26/11, 2012 at 22:21 Comment(9)
Have you redefined the t function in your workspace?Dana
i.e. as something like t <- function(...) rep(sqrt(.5), 2)Deist
Similar to this? stackoverflow.com/a/12019678Nerin
No I haven't, I don't know why its not working...Asceticism
Show us the output of methods(t)Nerin
Thanks to you all, the problem has been solved now....:)..I used rm() functionAsceticism
@JoshO'Brien - That's a ridiculous suggestion... nobody would write that function... Clearly it was t <- function(x){apply(x, 2, sd)} Torrance
@JoshO'Brien : why did you delete your answer? Looked good to me ..Crossstaff
@BenBolker -- 'cause it was wrong -- both parts of it! (That said, I'll undelete it: (a) as a monument to the stupidity of guaranteeing anything; and (b) because it's wrong in interesting ways.)Deist
G
12

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
Gillman answered 26/11, 2012 at 22:30 Comment(7)
That doesn't help if t.default is masked... or if there is a t.matrix method defined. ;-)Nerin
@Nerin -- It should help. base::t(xx) should look first in asNamespace("base"), where it'll find t.default() even if a function of the same name is registered elsewhere, right?Deist
No. methods defined in your globalenv() are used first.Nerin
Thank you both, but actually i am trying to generate a chi-square plot. The function i defined is qqplot<-function (xx) { n=length(xx[,1]);p=length(xx[1,]) xbar=colMeans(as.data.frame(xx));ss=var(xx) ssinv=solve(ss);d2=c() for (i in (1:n)){ xi=cbind(xx[i,]-xbar) d2=c(d2,t(xi)%*%ssinv%*%xi) } q=qchisq(((1:n)-0.5)/n,p) plot(q,sort(d2),type="p",pch=20,col="red",xlab="q",ylab="d^2",main="Chi-squa re Quantile Plot") }Asceticism
+1 for that point of widsom from Gsee on searching the globalenv first. Didn't know that.Attrition
@Nerin -- Not at all! Thanks for that. I'm also glad Ben nudged me to undelete.Deist
@Asceticism You're forming bad habits! qqplot is also a function in the stats package, which is loaded by default. As you've seen, creating functions with existing names can be very confusing; you should avoid it.Underpay
C
0

Maybe you can write your own function:

xx <- matrix(c(3,7,4,8), 2, byrow = TRUE)
transp <- function(n){
    TM <- matrix(, nrow = ncol(n), ncol = nrow(n))
        for (i in 1 : nrow(TM)){
            for (j in 1 : ncol(TM)){
                TM[i, j] <- n[j, i]
            }
        }
    print(TM)
} 
transp(xx)

Cowell answered 19/11, 2020 at 19:2 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.