周期序列是在n项后重复自身的序列,例如以下是周期序列:
1, 2, 3, 1, 2, 3, 1, 2, 3, ...
我们将该序列的周期定义为每个子序列中的项数(上面的子序列是 1、2、3)。所以上述序列的周期是 3。
在 R 中,我可以定义上述序列(尽管不是无穷大),使用:
sequence <- rep(c(1,2,3),n) #n is a predefined variable
Run Code Online (Sandbox Code Playgroud)
因此,如果n = 50,sequence将是序列 1, 2, 3, 1, 2, 3, ... , 1, 2, 3,其中每个数字都以明显的方式出现了 50 次。
我正在寻找构建一个函数来计算sequence. 伪代码如下:
period <- function(sequence){
subsequence <- subsequence(sequence) #identify the subsequence
len.subsequence <- length(subsequence) #calculate its length
return(len.subsequence) #return it
}
Run Code Online (Sandbox Code Playgroud)
我将如何识别子序列?这有点像rep函数的反转,这样我传入一个序列并传出初始向量的长度。
如果周期始终相同,即序列从不改变,那么您可以使用循环lag来查看匹配何时发生。
由于完全偏见,我还建议使用 seqle(猜猜谁写了该函数:-)),这就像rle但找到序列。 检测后续整数序列的间隔
我不是唯一一个以这种方式编辑“rle”源的人。