2017-04-09 89 views
-1

有一系列8,7,6,5,6,7,8,7,6,7,8其中5和6局部最小值。尋找系列的當地最小值

如何得到這個使用R?

+0

如果在5和6繪製,這個系列是雙傾角。這就是我的意思。糾正。 –

回答

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沒有跑,因爲是在問題的情況爲例,我們可以省略的三條線,消除了運行,並在最後的陳述與x取代xx。如果您不想考慮端點,請使用-Inf代替兩個出現的Inf

假設輸入c(2, 1, 1, 3)應該導致輸出1次。

+0

謝謝。幫了很多。 –

0

如果沒有運行,我們可以簡單地檢查與滯後和領先數之差:

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

給出:

[1] 5 6 
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