## Function to compute the Heat Index (Thermal comfort)
## Explanation: https://www.wpc.ncep.noaa.gov/html/heatindex_equation.shtml
## Function requires temperature data to be in Fahrenheit

HeatIndex <- function(T, RH) {
  
  ## Compute the simple Steadman formula
  simple_HI <- 0.5 * (T + 61.0 + ((T - 68.0) * 1.2) + (RH * 0.094))

  ## Average the simple HI with temperature
  avg_HI <- (simple_HI + T) / 2

  ## Full Rothfusz regression formula
  HI <- -42.379 + (2.04901523 * T) + (10.14333127 * RH) -
    (0.22475541 * T * RH) - (0.00683783 * T^2) -
    (0.05481717 * RH^2) + (0.00122874 * T^2 * RH) +
    (0.00085282 * T * RH^2) - (0.00000199 * T^2 * RH^2)

  ## Use the Steadman simple result where avg_HI < 80
  HI <- ifelse(avg_HI < 80, avg_HI, HI)

  ## Low humidity adjustment
  low_humid_cond <- (RH < 13) & (T >= 80) & (T <= 112)
  adjustment_low <- numeric(length = length(T))
  adjustment_low[low_humid_cond] <- ((13 - RH[low_humid_cond]) / 4) *
    sqrt((17 - abs(T[low_humid_cond] - 95)) / 17)
  HI <- HI - adjustment_low

  ## High humidity adjustment
  high_humid_cond <- (RH > 85) & (T >= 80) & (T <= 87)
  adjustment_high <- numeric(length = length(T))
  adjustment_high[high_humid_cond] <- ((RH[high_humid_cond] - 85) / 10) *
    ((87 - T[high_humid_cond]) / 5)
  HI <- HI + adjustment_high

  return(HI)
}
