lserlohn lserlohn - 3 months ago 7
R Question

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.
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.

AEF AEF
Answer

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)
}
Comments