shift matrix elements in R
n <- 5
a <- matrix(c(1:n**2),nrow = n, byrow = T)
output is
[,1] [,2] [,3] [,4] [,5]
[1,] 1 2 3 4 5
[2,] 6 7 8 9 10
[3,] 11 12 13 14 15
[4,] 16 17 18 19 20
[5,] 21 22 23 24 25
how do I shift the '1' to the current position of '25' to look like this:
[,1] [,2] [,3] [,4] [,5]
[1,] 2 3 4 5 6
[2,] 7 8 9 10 11
[3,] 12 13 14 15 16
[4,] 17 18 19 20 21
[5,] 22 23 24 25 1
a <- t(a); a[] <- c(a[-1], a[1]); a <- t(a)
a
# [,1] [,2] [,3] [,4] [,5]
# [1,] 2 3 4 5 6
# [2,] 7 8 9 10 11
# [3,] 12 13 14 15 16
# [4,] 17 18 19 20 21
# [5,] 22 23 24 25 1
-
c(a)
unwinds or unlists the matrix into a vector. It does this column-first, soc(a)
results in[1] 1 6 11 16 21 2 ...
. We want it to be row-first, though, so -
t(a)
transposes it, so that what was a row-first is now column-first, allowingc(a)
and such to work. -
c(a[-1], a[1])
is just "concatenate all except the first with the first", the classic way to put the first element of avector
at the end. -
a[] <-
is a way to do calcs on its values where the calcs do not preserve the "dimensionality" of the object. - After we've rearranged, we then
t
ranspose back to the original shape and row/column-order.