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.
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.
Have a look at the structure using
str
:The final transpose operation sends the vector
a
to a matrix with 20 rows and 1 column. Equivalent to: