-1

有一个系列 8,7,6,5,6,7,8,7,6,7,8 在 5 和 6 处具有局部最小值。

如何使用 R 得到这个?

4

3 回答 3

3
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 一次。

于 2017-04-09T11:44:43.687 回答
0

如果没有运行,我们可以简单地检查滞后和领先数字的差异:

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

给出:

[1] 5 6
于 2017-04-09T11:54:37.430 回答
0

我尝试不使用任何软件包并得到结果。

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
于 2017-04-09T12:41:44.323 回答