gpt4 book ai didi

r - 测量数字序列的周期性 [R]

转载 作者:行者123 更新时间:2023-12-04 09:50:11 25 4
gpt4 key购买 nike

周期序列是在 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

所以如果 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
}

我将如何识别子序列?这有点逆转 rep函数,这样我传入一个序列并传出初始向量的长度。

最佳答案

如果周期始终相同,即序列永远不会改变,那么您可以在 lag 上使用循环查看何时发生匹配。

对于完全偏差,我还建议使用 seqle (猜猜那个函数是谁写的 :-) ),就像 rle但找到序列。 detect intervals of the consequent integer sequences
我不是唯一一个以这种方式编辑“rle”源代码的人。

关于r - 测量数字序列的周期性 [R],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12824931/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com