【发布时间】:2016-12-15 17:59:20
【问题描述】:
我想创建一个序列号向量,例如:
1,2,3,4,5, 2,3,4,5,1, 3,4,5,1,2
在一个序列完成后(例如,rep(seq(1,5),3)),前一个序列的第一个数字现在移动到序列中的最后一个位置。
【问题讨论】:
我想创建一个序列号向量,例如:
1,2,3,4,5, 2,3,4,5,1, 3,4,5,1,2
在一个序列完成后(例如,rep(seq(1,5),3)),前一个序列的第一个数字现在移动到序列中的最后一个位置。
【问题讨论】:
%% 取模?
(1:5) %% 5 + 1 # left shift by 1
[1] 2 3 4 5 1
(1:5 + 1) %% 5 + 1 # left shift by 2
[1] 3 4 5 1 2
也试试
(1:5 - 2) %% 5 + 1 # right shift by 1
[1] 5 1 2 3 4
(1:5 - 3) %% 5 + 1 # right shift by 2
[1] 4 5 1 2 3
【讨论】:
我会先制作一个比系列长度长的一列矩阵。
> lseries <- 5
> nreps <- 3
> (values <- matrix(1:lseries, nrow = lseries + 1, ncol = nreps))
[,1] [,2] [,3]
[1,] 1 2 3
[2,] 2 3 4
[3,] 3 4 5
[4,] 4 5 1
[5,] 5 1 2
[6,] 1 2 3
这可能会引发您可以忽略的警告 (In matrix(1:lseries, nrow = lseries + 1, ncol = nreps) : data length [5] is not a sub-multiple or multiple of the number of rows [6])。请注意,第一行 1:lseries 包含您想要的数据。我们可以使用以下方法获得最终结果:
> as.vector(values[1:lseries, ])
[1] 1 2 3 4 5 2 3 4 5 1 3 4 5 1 2
【讨论】:
这是获取每个矩阵的方法
matrix(1:5, 5, 6, byrow=TRUE)[, -6]
[,1] [,2] [,3] [,4] [,5]
[1,] 1 2 3 4 5
[2,] 2 3 4 5 1
[3,] 3 4 5 1 2
[4,] 4 5 1 2 3
[5,] 5 1 2 3 4
或者把它变成一个列表
split.default(matrix(1:5, 5, 6, byrow=TRUE)[, -6], 1:5)
$`1`
[1] 1 2 3 4 5
$`2`
[1] 2 3 4 5 1
$`3`
[1] 3 4 5 1 2
$`4`
[1] 4 5 1 2 3
$`5`
[1] 5 1 2 3 4
或者用c进入一个向量
c(matrix(1:5, 5, 6, byrow=TRUE)[, -6])
[1] 1 2 3 4 5 2 3 4 5 1 3 4 5 1 2 4 5 1 2 3 5 1 2 3 4
为了多样化,这里有第二种返回向量的方法:
# construct the larger vector
temp <- rep(1:5, 6)
# use sapply with which to pull off matching positions, then take select position to drop
temp[-sapply(1:5, function(x) which(temp == x)[x+1])]
[1] 1 2 3 4 5 2 3 4 5 1 3 4 5 1 2 4 5 1 2 3 5 1 2 3 4
【讨论】: