1

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"

NVega
  • 81
  • 9
  • 3
    It would be nice if you could include some sample data, not just the column names, see e.g. [this post](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example). That will make it easier to find the correct answer. – talat May 21 '14 at 16:26

1 Answers1

3

Given:

  • data frame df with a complete record for every single day for the time period under study
  • df$Temp field with the temperature
  • min_temp, the minimum temperature, to test in df$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