简体   繁体   中英

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, so c(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, allowing c(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 a vector 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.

Here is a base R one-liner

> t(`dim<-`(t(a)[seq_along(a)%%length(a)+1],rev(dim(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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM