Why does this code transpose a vector twice - is it noop?

I have some old R code that does:

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

What does this code do? Looks like me. ais a vector based on c(1:20).

Edit: bonus points on how to do it better.

+4
source share
2 answers

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 ato a matrix with 20 rows and 1 column. Equivalent to:

c <- as.matrix(c(1:20))
+5
source

I think it’s clearer to explicitly set sizes instead of double t():

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

which should avoid making a copy.

I saw this quite a bit in the older code, for example, for least squares, you can start with:

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

, , , :

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

x ,

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

t() - ; , solve(crossprod(x), crossprod(x,y)), .

+4

All Articles