R-如果存在多个条件,则进行向量化 [英] R - vectorized if for multiple conditions

查看:42
本文介绍了R-如果存在多个条件,则进行向量化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图按照以下表达式来计算取决于三个不同温度的热应力指数:

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

对于单个温度值,我的R实现工作正常:

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

但是,如果我尝试为 Teff 的范围计算 hsa ,如下所示:

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

Teff=seq(30,40,1)

我收到以下警告:

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

这显然是因为 if()未向量化,因此仅求值向量的第一个元素.

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

我了解了 ifelse(),它是向量化的 if(),但是我不确定如何将其用于多种条件.

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

所以,我的问题是:使用向量而不是标量来计算我的 hsa 索引的另一种矢量化方法是什么?

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

推荐答案

如何?

与上面的功能相同,但是没有显式的 if else ?

It's the same function as above, but without the explicit if and else?

> Teff=seq(30,40,1)
> hsa<- 1*(Teff<Tcr) + (1 - (Teff - Tcr)/(Tlim - Tcr))*(Teff >= Tcr & Teff < Tlim)
> hsa
 [1] 1.0000000 1.0000000 1.0000000 1.0000000 0.8571429 0.7142857 0.5714286 0.4285714 0.2857143 0.1428571 0.0000000

**请注意,您可以在最后添加 + 0 *(Teff> = Tlim),但这不会更改任何内容,因为分配的值始终为0.

** Note that you can add + 0*(Teff>=Tlim) in the end, but it wouldn't change anything, because the assigned value would be 0 anyways.

如果您真的想使用 ifelse ,则必须嵌套它们,因此应该是这样的:

If you really want to use ifelse, then you have to nest them, so it should be something like this:

> hsa<- ifelse(Teff<Tcr, 1,
               ifelse(Teff >= Tcr & Teff < Tlim, 
               (1 - (Teff - Tcr)/(Tlim - Tcr)), 0))
> hsa
     [1] 1.0000000 1.0000000 1.0000000 1.0000000 0.8571429 0.7142857 0.5714286 0.4285714 0.2857143 0.1428571 0.0000000

这篇关于R-如果存在多个条件,则进行向量化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆