r语言 - 查找序列的局部最小值



有一个序列8,7,6,5,6,7,8,7,6,7,8,8的局部最小值为5和6。

如何使用R获得它?

library(zoo)
x <- c(8,7,6,5,6,7,8,7,6,7,8)
# eliminate runs
r <- rle(x)
r$lengths[] <- 1
xx <- inverse.rle(r)        
xx[ rollapply(c(Inf, xx, Inf), 3, function(x) x[2] < min(x[-2])) ]
## [1] 5 6

如果我们知道x没有运行,就像问题示例中的情况一样,我们可以省略消除运行的三行,并将最后一个语句中的xx替换为x。 如果不想考虑终结点,请使用 -Inf 代替两次出现的Inf

假设输入c(2, 1, 1, 3)应产生一次输出 1。

如果没有运行,我们可以简单地用滞后和前导数检查差异:

library(dplyr)
x[x - lag(x) < 0 & x - lead(x) < 0]

给:

[1] 5 6

我尝试在没有任何包的情况下使用并得到了结果。

series<-c(8,7,6,5,6,7,8,7,6,7,8)
#We have local minima at 5 and 6.
#Check if series is decreasing in the begining itself
series[2]<series[1]
#If so let us check for minima.
#First check if you have multiple minima
less<-numeric()
#Fill first position and write a loop to check rest of positions.
less<-1
for(i in 2:length(series)){
less[i]<-ifelse(series[i-1]>=series[i],1,0)
}
#First occurance of 0 after 1
checkless<-numeric()
#Fill first position and write a loop to check rest of positions.
checkless<-1
for(i in 2:length(less)){
  checkless[i]<-ifelse(less[i-1]==0,1,less[i])
}
#Indexes where 0 exists indicates the change in signs.
which(checkless==0)
#Local minima exists once index before change
which(checkless==0)-1
series[which(checkless==0)-1]
#Check how many cases exists
length(series[which(checkless==0)])
#If number of such cases greater than 1 then we have multiple minima in the series
length(series[which(checkless==0)])>1

最新更新