对于这个问题,我并不是在寻找一个谷,而是一种识别数字序列中重复的“谷”的方法。
我有这些数据
x <- c(1,1,2,2,1,1,2,2,3,3,3,2,2,2,3)因此,我尝试了以下方法:
test <- data.frame(x)
test <- test %>% mutate(Lag = c(tail(x, -1), NA))
which(test$x > test$Lag)+1我得到了5号和12号的位置。
问题是,我如何获得代码来识别数字序列中剩余的“谷”。预期输出将识别位置5,6和12,13,14。
它有点类似于时间序列中的局部最小值,但这不是我要找的。
我还想将这些识别为块;5,6的位置属于类别1,12,13,14属于类别2。
提前谢谢你!
发布于 2017-03-13 13:02:58
我们也可以使用base R的rle来实现这一点
v1 <- seq_along(x)*inverse.rle(within.list(rle(x),
{i1 <- c(0, diff(values))<0; values <- i1}))
v1[v1!=0]
#[1] 5 6 12 13 14发布于 2017-03-13 12:56:46
这个问题可以使用cummax来解决。使用你的x,
cummax(x)
# [1] 1 1 2 2 2 2 2 2 3 3 3 3 3 3 3
which(x != cummax(x))
# [1] 5 6 12 13 14
x[x != cummax(x)]
# [1] 1 1 2 2 2给你5-6和12-14,然后你就知道每一个都被分配到了哪个类别。您可以使用split或某种装箱函数对它们进行分组,这可能更有意义。
发布于 2017-03-13 16:04:42
我们可以使用正则表达式(valley指的是negative slope后跟0 slopes,然后是x中的positive slope,假设坡度是-1, 0和1,就像在输入数据中一样,但我们可以推广):
pattern <- 'N([0]+)P' # \_.._/
txt <- gsub('1', 'P', gsub('-1', 'N', paste(diff(x), collapse='')))
matched <- gregexpr(pattern,txt)
positions <- unlist(matched) + 1
lengths <- attr(matched[[1]], "match.length") - 2 # exclude N & P
valley.points <- lapply(1:length(positions), function(i)seq(positions[i], positions[i]+lengths[i],1))
#[[1]]
#[1] 5 6
#[[2]]
#[1] 12 13 14
plot(x, type='l')
points(unlist(valley.points), x[unlist(valley.points)], pch=19, col='red')

https://stackoverflow.com/questions/42756559
复制相似问题