Why does this code double transpose a vector - is this a noop?

556 views Asked by At

I have some legacy R code that does:

b = t(a)
c = t(b)

What does this code do? Looks like a noop to me. a is a vector constructed by c(1:20).

Edit: bonus points on how to do this better.

2

There are 2 answers

3
Alex On BEST ANSWER

Have a look at the structure using str:

> str(a); str(b); str(c)
 int [1:20] 1 2 3 4 5 6 7 8 9 10 ...
 int [1, 1:20] 1 2 3 4 5 6 7 8 9 10 ...
 int [1:20, 1] 1 2 3 4 5 6 7 8 9 10 ...

The final transpose operation sends the vector a to a matrix with 20 rows and 1 column. Equivalent to:

c <- as.matrix(c(1:20))
0
Neal Fultz On

I think it's clearer to explicitly set dimensions instead of double t():

dim(a) <- c(length(a), 1)

which should avoid making a copy.

I've seen this quite a bit in older code, eg for least squares, one might start with:

solve(t(x) %*% x) %*% t(x) %*% y

and, thinking it will save a transpose, refactor to:

xt <- t(x)
solve(xt %*% x) %*% xt %*% y

and if x isn't necessarily a matrix yet,

xt <- t(a)
x <- t(xt)

but t()s are somewhat of a code smell; in this case you are really better off using the other matrix operations eg solve(crossprod(x), crossprod(x,y)) instead, which gives the same result with less overhead.