如果你總是可以依靠的間距是一個月內,然後讓我們暫時拋卻時間信息:
temps <- Nino3.4_1974_2000$Nino3.4_degree_1974_2000_plain
所以,因爲在每一個溫度該向量是總是相隔一個月,我們只需要尋找temps[i]>=0.5
的運行,並且運行必須至少5個長。
如果我們做到以下幾點:
ofinterest <- temps >= 0.5
我們只好值TRUE FALSE FALSE TRUE TRUE ....
等載體ofinterest
它的TRUE
時temps[i]
爲> = 0.5和FALSE
否則。
要重新解釋您的問題,那麼我們只需要查看的發生次數,連續至少有5個TRUE
連續。
要做到這一點,我們可以使用函數rle
。 ?rle
給出:
> ?rle
Description
Compute the lengths and values of runs of equal values in a vector
- or the reverse operation.
Value:
‘rle()’ returns an object of class ‘"rle"’ which is a list with
components:
lengths: an integer vector containing the length of each run.
values: a vector of the same length as ‘lengths’ with the
corresponding values.
因此我們使用rle
它計算了所有的連續和連續TRUE
條紋成一排連續FALSE
,並連續尋找至少5 TRUE
。
我只是做了一些數據來證明:
# for you, temps <- Nino3.4_1974_2000$Nino3.4_degree_1974_2000_plain
temps <- runif(1000)
# make a vector that is TRUE when temperature is >= 0.5 and FALSE otherwise
ofinterest <- temps >= 0.5
# count up the runs of TRUEs and FALSEs using rle:
runs <- rle(ofinterest)
# we need to find points where runs$lengths >= 5 (ie more than 5 in a row),
# AND runs$values is TRUE (so more than 5 'TRUE's in a row).
streakIs <- which(runs$lengths>=5 & runs$values)
# these are all the el_nino occurences.
# We need to convert `streakIs` into indices into our original `temps` vector.
# To do this we add up all the `runs$lengths` up to `streakIs[i]` and that gives
# the index into `temps`.
# that is:
# startMonths <- c()
# for (n in streakIs) {
# startMonths <- c(startMonths, sum(runs$lengths[1:(n-1)]) + 1
# }
#
# However, since this is R we can vectorise with sapply:
startMonths <- sapply(streakIs, function(n) sum(runs$lengths[1:(n-1)])+1)
現在,如果你這樣做Nino3.4_1974_2000$Month_common[startMonths]
你會得到其中的厄爾尼諾開始的所有月份。
它歸結爲短短的幾行:
runs <- rle(Nino3.4_1974_2000$Nino3.4_degree_1974_2000_plain>=0.5)
streakIs <- which(runs$lengths>=5 & runs$values)
startMonths <- sapply(streakIs, function(n) sum(runs$lengths[1:(n-1)])+1)
Nino3.4_1974_2000$Month_common[startMonths]
是*永遠*一個你本月'Month_common'行之間的區別是什麼? – 2012-01-18 05:20:06
是的,間距是一個月。 – 2012-01-18 05:25:04