异常测序

问题描述:

我想创建有序号码如的向量:异常测序

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 
+0

有趣的想法! – Stedy

这里的方法来获取每一种

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 

我会通过使一列的矩阵比的长度长开始系列。

> 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