假设我的矢量数包含c(1,2,3,5,7,8),我希望找到它是否包含3个连续数字,在这种情况下,它们是1,2,3.
numbers = c(1,2,3,5,7,8)
difference = diff(numbers) //The difference output would be 1,1,2,2,1
Run Code Online (Sandbox Code Playgroud)
为了验证我的数字向量中有3个连续的整数,我尝试了以下几点奖励.
rep(1,2)%in%difference
Run Code Online (Sandbox Code Playgroud)
上面的代码适用于这种情况,但如果我的差异向量=(1,2,2,2,1),即使"1"不是连续的,它仍然会返回TRUE.
我很确定你们都同意这rle是R中那些"陷阱"函数之一.是否有任何类似的函数可以"捕获"相邻整数值的"运行"?
所以,如果我有一个像这样的矢量:
x <- c(3:5, 10:15, 17, 22, 23, 35:40)
Run Code Online (Sandbox Code Playgroud)
我称之为深奥的功能,我会得到这样的响应:
lengths: 3, 6, 1, 2, 6
values: (3,4,5), (10,11,12... # you get the point
Run Code Online (Sandbox Code Playgroud)
编写这样的函数并不难,但仍然......任何想法?
周期序列是在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函数的反转,这样我传入一个序列并传出初始向量的长度。
Is it possible to count a repeating part of a sequence in R? For example:
x<- c(1,3.0,3.1,3.2,1,1,2,3.0,3.1,3.2,4,4,5,6,5,3.0,3.1,3.2,
3.1,2,1,4,6,4.0,4,3.0,3.1,3.2,5,3.2,3.0,4)
Run Code Online (Sandbox Code Playgroud)
Is it possible to count the times that the subsequence 3.0,3.1,3.2 occurs? So in this example it must be: 4
我在表单中有一个data.frame:
Date
2011-08-16
2011-08-17
2011-08-28
2011-09-01
2011-09-05
2011-09-06
2011-10-01
2011-10-02
2011-10-03
2011-10-04
Run Code Online (Sandbox Code Playgroud)
我想做的是在日期顺序发生时进行运行计数,即它们是并排的.
在上面的例子中,我们将有2,1,1,2,4
如果我有一个数字向量[1 2 3 4 7 8 9 10 15 16 17],我该如何拆分它以便我返回多个向量来分隔该向量的连续元素?即[1 2 3 4] [7 8 9 10] [15 16 17].我在matlab中找到了如何做到这一点的答案,但我只使用了R.
谢谢.