有一系列8,7,6,5,6,7,8,7,6,7,8在5和6处有局部最小值。
如何使用R?
答案 0 :(得分: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次。
答案 1 :(得分:0)
如果没有运行,我们可以简单地检查滞后和前导数字的区别:
library(dplyr)
x[x - lag(x) < 0 & x - lead(x) < 0]
给出:
[1] 5 6
答案 2 :(得分: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