简体   繁体   English

在R中具有数组输入的if-else语句

[英]if-else statement with array input in R

I want to write a custom threshold function like that: 我想编写一个自定义阈值函数,例如:

doubleThres <- function(value)
{
  if(value >=0.8)
  {
    value = value * 0.8

  }

  if( value < 0.5)
  {
    value = max(value * 1.2, value + 0.1)
  }
  return(value)
}

If I input one single value like 1.2, then the function works fine. 如果我输入一个像1.2这样的单个值,则该函数可以正常工作。 However, I want to input an array, which was one column of the data frame. 但是,我想输入一个数组,它是数据帧的一列。

doubleThres(myDataFrame$value)

Then it would report error. 然后它将报告错误。

In if (vale >= 0.8) { :
  the condition has length > 1 and only the first element will be used

I know the function has problem, but I don't know how to correct it in a simple way, without using for-loop in the function. 我知道该函数有问题,但是我不知道如何在不使用for循环的情况下以简单的方式纠正它。

There were already suggestions in the comments that would work, but if you want to keep the structure of your function you can use logical indexing: 注释中已经有一些建议可以使用,但是如果您想要保留函数的结构,则可以使用逻辑索引:

doubleThres <- function(value)
{
    value[value >= 0.8] <- value[value >= 0.8] * 0.8
    value[value < 0.5] <- pmax(value[value < 0.5] * 1.2, value[value < 0.5] + 0.1)
    return(value)
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM