如果你总是可以依靠的间距是一个月内,然后让我们暂时抛却时间信息:
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