I have a data of temperatutre and I want to get the number of 4 consecutives days with this condition (Temp > Tmax) for each year I have. For an illustrative example consider the following data frame of 5 columns: "Station Temp Year Month Day"
Asked
Active
Viewed 1,189 times
1 Answers
3
Given:
- data frame
df
with a complete record for every single day for the time period under study df$Temp
field with the temperaturemin_temp
, the minimum temperature, to test indf$Temp > min_temp
min_days
, the minimum number of consecutive days
This will yield the number of "heat waves" during the time period:
count.heat.waves <- function(df, min_temp, min_days) {
sum(with(rle(df$Temp > min_temp), values & lengths >= min_days))
}
For example:
data(airquality)
count.heat.waves(airquality, 70, 4) # yields 3
If you want to get this value for each year, you need to partition your data by year. Be careful with dealing with the beginning and end of years. For example what if a "heat waves" started at the end of one year and ended in the beginning of the next. It will not be counted for either of them.

janos
- 120,954
- 29
- 226
- 236