什么是连续数字检测n模式最有效的方法? 也许是一个SQL列或向量,R。 一些伪代码-R-来说明“问题”:
find Pattern in consecutive integers, where
2nd integer < 1st integer,
3rd integer > 2nd integer &
4th integer > 3rd integer.
a <- x
b <- x +1 < a
c <- x +2 > b
d <- x +3 > c
pattern <- c(a, b, c, d)
example: pattern <- c(10, 8, 9, 11) or pattern <- c(2.11, 2.08, 2.09, 2.11)
count(pattern)
find(pattern)
答案 0 :(得分:2)
如果你取矢量的差值,那么第一个应该是负数而另外两个是正数,所以,
a <- c(10, 8, 9, 11)
all((diff(a) < 0) == c(TRUE, FALSE, FALSE))
#[1] TRUE
要将其应用于更大的向量,您可以使用rollapply
包中的zoo
,即
library(zoo)
a <- sample(1:100,100,replace=T)
unique(rollapply(a, 4, by = 1, function(i) i[all((diff(i) < 0) == c(TRUE, FALSE, FALSE))]))
给出,
[,1] [,2] [,3] [,4] [1,] 85 18 85 92 [2,] 44 27 67 76 [3,] 58 2 39 54 [4,] 85 69 82 84 [5,] 61 4 40 44 [6,] 65 58 73 97 [7,] 19 9 92 96 [8,] 33 24 57 73 [9,] 79 11 37 100