简体   繁体   English

移位 R 中的矩阵元素

[英]shift matrix elements in R

n <- 5
a <- matrix(c(1:n**2),nrow = n, byrow = T)

output is output 是

     [,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”转换为“25”的当前 position 看起来像这样:

     [,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. c(a)将矩阵展开或展开为向量。 It does this column-first, so c(a) results in [1] 1 6 11 16 21 2... .它首先执行此列,因此c(a)导致[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. t(a)对其进行转置,因此行优先现在列优先,从而允许c(a)等工作。
  • 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. c(a[-1], a[1])只是“将除第一个之外的所有元素与第一个连接起来” ,这是将vector的第一个元素放在末尾的经典方法。
  • a[] <- is a way to do calcs on its values where the calcs do not preserve the "dimensionality" of the object. a[] <-是一种对其进行计算的方法,其中计算不保留 object 的“维数”。
  • After we've rearranged, we then t ranspose back to the original shape and row/column-order.在我们重新排列之后,我们将t回原始形状和行/列顺序。

Here is a base R one-liner这里是基础 R 单线

> 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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