mardi 9 mai 2017

R - vectorized if for multiple conditions

I am trying to calculate a heat stress index that depends on three distinct temperatures, following this expression:

enter image description here

My R implementation works OK for single temperature values:

# Set temperatures
Teff=34
Tcr=33
Tlim=40

# Apply conditions
if (Teff < Tcr) {
  hsa = 1
} else if (Teff >= Tcr & Teff < Tlim) {
  hsa = 1 - ((Teff - Tcr)/(Tlim - Tcr))
} else if (Teff >= Tlim) {
  hsa = 0
}

hsa
  [1] 0.8571429

However, if I try to calculate hsa for a range of Teff, like this:

Teff=seq(30,40,1)

I get the following warning:

Warning message:
In if (Teff < Tcr) { :
  the condition has length > 1 and only the first element will be used

Which apparently occurs because if() is not vectorized and therefore evaluates only the first element of the vector.

I learned about ifelse(), which is vectorized if(), but I'm not sure how it can be used for multiple conditions.

So, my question is: what would be an alternative, vectorized way to calculate my hsa index using vectors instead of scalars?

Aucun commentaire:

Enregistrer un commentaire